迭代特定元素的嵌套对象结构

时间:2016-11-23 22:36:51

标签: javascript

我有以下嵌套对象。什么是最简单的方法来获得所有"范围"数组中的值,而不单独引用它们,

JSONObject["inc"]["scope"]

对象:

[{
    "inc": [{
        "type": "Entity",
        "scope": "A"
    }, {
        "type": "Entity",
        "scope": "B"
    }],
    "inv": [{
        "type": "Entity",
        "scope": "C"
    }],
    "oth": [{
        "type": "Entity",
        "scope": "D"
    }],
    "pro": [{
        "type": "Support Dept",
        "scope": "E"
    }, {
        "type": "Entity",
        "scope": "F"
    }, {
        "type": "Entity",
        "scope": "C"
    }],
    "ap": [{
        "type": "Support Dept",
        "scope": "A"
    }]
}]

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

以下是如何做到这一点:

var obj = [{
    "inc": [{
        "type": "Entity",
        "scope": "A"
    }, {
        "type": "Entity",
        "scope": "B"
    }],
    "inv": [{
        "type": "Entity",
        "scope": "C"
    }],
    "oth": [{
        "type": "Entity",
        "scope": "D"
    }],
    "pro": [{
        "type": "Support Dept",
        "scope": "E"
    }, {
        "type": "Entity",
        "scope": "F"
    }, {
        "type": "Entity",
        "scope": "C"
    }],
    "ap": [{
        "type": "Support Dept",
        "scope": "A"
    }]
}];
    
res =  Object.keys(obj[0]).reduce(function (acc, key) {
    return acc.concat(obj[0][key].map (function (o) {
        return o.scope;
    }));
}, []);

console.log(res);

请不要调用变量JSONObject。哪有这回事。 JSON是用于数据交换的文本格式。你拥有的是一个JavaScript对象,它可能是从你解析的JSON派生出来的,但它不是JSON。

答案 1 :(得分:1)

试试这个:



var obj = [{
  "inc": [{
    "type": "Entity",
    "scope": "A"
  }, {
    "type": "Entity",
    "scope": "B"
  }],
  "inv": [{
    "type": "Entity",
    "scope": "C"
  }],
  "oth": [{
    "type": "Entity",
    "scope": "D"
  }],
  "pro": [{
    "type": "Support Dept",
    "scope": "E"
  }, {
    "type": "Entity",
    "scope": "F"
  }, {
    "type": "Entity",
    "scope": "C"
  }],
  "ap": [{
    "type": "Support Dept",
    "scope": "A"
  }]
}];

var arr = [];
for (var i in obj[0]) {
  for (var j in obj[0][i]) {
    arr.push(obj[0][i][j]["scope"])
  }
}
console.log(arr)




答案 2 :(得分:1)

我将采取的一种方法是功能性方法。

<强> ES2015

let scopes = obj.reduce((start ,item) => {
  start = Object.keys(item).map(e => item[e]);
  return start.concat.apply([] , start).map( e => e.scope);
},[]);
console.log('ES2015',scopes);

<强> ES5

var scopes = obj.reduce(function(start ,item){
  start = Object.keys(item).map(function(e){
    return item[e];
  })
  return start.concat.apply([] , start).map(function(e){
    return e.scope
  });
},[]);

console.log('ES5',scopes)