如何将数组块组合成一个数组

时间:2017-09-07 10:51:11

标签: javascript html arrays json

我有什么:

var json = {
  key1: 'value1',
  key2: 'value2',
  key3: {
    title: 'yeah'
  }
}

var path = ['key3', 'title'];

我想要的是结合“路径”的块。数组有一个json的路径:

return json['key3']['title'];

1 个答案:

答案 0 :(得分:0)

您可以对路径元素进行迭代,并找到正确的位置,如下所示:



var json = {
  key1: 'value1',
  key2: 'value2',
  key3: {
    title: 'yeah'
  }
}

var path = ['key3', 'title'];

function getPath(json, ...path){
  if(Array.isArray(path[0])){ path = path[0];}
  var i = 0;
  while(path.length > i){
    var key = path[i++];
    json = json[key];
    if(json === undefined) return undefined;
  }
  return json;
}

console.log(getPath(json, path));
console.log(getPath(json, ...path));
console.log(getPath(json, 'key3', 'title'));
console.log(getPath(json, 'key1', 'title'));
console.log(getPath(json, 'doesNotExsist', 'title'));
console.log(getPath(json, 'key1'));