从内部对象获取价值

时间:2017-07-11 07:11:41

标签: javascript

这是我的JSON object

[{"dataset": {"item": [{"key1": "'key1'","key2": "value1"},
                   {"key1": "'key1'","key2": "value2"},
                   {"key1": "'key1'","key2": "value3"}]}},
 {"dataset": {"dataset": { "dataset": { "item": [{"key1": "key1","key2": "value4"}]}}}}]

如何从所有节点获取'key2'值。在对象中它仍然有更多的节点。

2 个答案:

答案 0 :(得分:1)

这听起来像是custom reviver

的工作

var json = `[{"dataset": {"item": [{"key1": "'key1'","key2": "value1"},
                   {"key1": "'key1'","key2": "value2"},
                   {"key1": "'key1'","key2": "value3"}]}},
 {"dataset": {"dataset": { "dataset": { "item": [{"key1": "key1","key2": "value4"}]}}}}]`

var result = []

// Traverse all nodes and collect key2 values.
JSON.parse(json, function(key, value) {
  if (key === 'key2') {
    result.push(value)
  }
  if (key === 'item') {
    console.log(value)
  }
  return value
})

console.log(result)

答案 1 :(得分:1)

您也可以使用Object.keys执行此操作并递归遍历节点。



var json = [{"dataset": {"item": [{"key1": "'key1'","key2": "value1"},
                   {"key1": "'key1'","key2": "value2"},
                   {"key1": "'key1'","key2": "value3"}]}},
 {"dataset": {"dataset": { "dataset": { "item": [{"key1": "key1","key2": "value4"}]}}}}];
 
let res = [];
for(prop in json){
  const recursive = (obj, targetKey) => {
    Object.keys(obj).forEach(function (key) {
      if (key === targetKey) {
          res.push(obj[key]);
      } else {
        if (typeof obj[key] === 'object') {
          recursive(obj[key], targetKey);
        }
      }
    });
  };
  
  recursive(json[prop], 'key2');
}
console.log('res', res)