我是reactjs
和javascript的新手。
在这里,我有一个对象数组,
[
{
"id": "CSS",
"questionCount": [
{
"level": "TOUGH",
"type": "NON_CODE",
"count": "1"
}
]
},
{
"id": "Backbone",
"questionCount": [
{
"level": "TOUGH",
"type": "CODE",
"count": "2"
},
{
"level": "TOUGH",
"type": "NON_CODE",
"count": "5"
},
{
"level": "MEDIUM",
"type": "NON_CODE",
"count": "7"
},
{
"level": "EASY",
"type": "NON_CODE",
"count": "6"
}
]
},
]
现在,我想要的是拥有一个对象数组,该对象数组将包含questionCount
数组中存在的所有对象。
所以,就像
[ {
"level": "TOUGH",
"type": "NON_CODE",
"count": "1"
}, {
"level": "TOUGH",
"type": "CODE",
"count": "2"
},
{
"level": "TOUGH",
"type": "NON_CODE",
"count": "5"
},
{
"level": "MEDIUM",
"type": "NON_CODE",
"count": "7"
},
{
"level": "EASY",
"type": "NON_CODE",
"count": "6"
} ]
那么,有人可以帮我吗?
答案 0 :(得分:6)
您可以将Array.prototype.reduce()与Array.prototype.concat()结合使用:
const temp = [{"id": "CSS","questionCount": [{"level": "TOUGH","type": "NON_CODE","count": "1"}]},{"id": "Backbone","questionCount": [{"level": "TOUGH","type": "CODE","count": "2"},{"level": "TOUGH","type": "NON_CODE","count": "5"},{"level": "MEDIUM","type": "NON_CODE","count": "7"},{"level": "EASY","type": "NON_CODE","count": "6"}]},];
const result = temp.reduce((a, c) => a.concat(c.questionCount), []);
console.log(result);
答案 1 :(得分:3)
您可以遍历每个元素,并将其与结果连接。 尝试以下操作:
var jsonObject = [{"id": "CSS","questionCount": [{"level": "TOUGH","type": "NON_CODE","count": "1"}]},{"id": "Backbone","questionCount": [{"level": "TOUGH","type": "CODE","count": "2"},{"level": "TOUGH","type": "NON_CODE","count": "5"},{"level": "MEDIUM","type": "NON_CODE","count": "7"},{"level": "EASY","type": "NON_CODE","count": "6"}]}]
var result = [];
for(var t of jsonObject){
if(t.questionCount){
//As t.questionCount is an array, we need to add property to each of the element present in that array
t.questionCount.forEach(obj => obj.Id = t.id);
result = result.concat(t.questionCount);
}
}
console.log(result);
答案 2 :(得分:1)
让我们说给temp一个数组,那么您可以使用以下代码对问题计数数组:-
finalArr=[]
for(var i=0;i<temp.length;i++)
finalArray.push(temp[i].questionCount)
答案 3 :(得分:0)
这点代码的和平就可以做到
var newData = [];
for (var i of data) {
newData = newData.concat(i['questionCount'])
}
答案 4 :(得分:0)
通过ES6减少和传播,您可以执行以下操作
const x = arr.reduce((accum, curr) => {
let newArr = [...accum, ...curr.questionCount];
return newArr
}, [])
答案 5 :(得分:0)
// -- Use the swiss-knife-tool :-) (Lodash)
// -- Taking x as your array in the question,
// -- you can use lodash to map specific attribute
// -- and then flatten the output array.
const y = _
.chain(x)
.map(item => item.questionCount)
.flatten()
.value();
console.log(y);