这是我的阵列
[
{
'data': [
{
'value': 'Red'
},
{
'value': 'Small'
},
{
'value': 'Good'
}
]
},
{
'data': [
{
'value': 'Black'
},
{
'value': 'Medium'
},
{
'value': 'Bad'
}
]
},
{
'data': [
{
'value': 'White'
},
{
'value': 'Large'
},
{
'value': 'Best'
}
]
}
]
我想要
[
['Red', 'Black', 'White'], // all values from first index
['Small', 'Medium', 'Large'], // all values from second index
['Good', 'Bad', 'Best'] // all values from third index
]
我尝试过forEach
,for...in
,filter
等。但是我没有成功获得这个输出
你可以使用reduce()
然后在reduce循环中使用forEach()
。在forEach
循环中,使用索引来确定要推送的数组。它在该索引上没有任何价值,创建一个新数组并推进:
let data = [{'data': [{'value': 'Red'},{'value': 'Small'},{'value': 'Good'}]},{'data': [{'value': 'Black'},{'value': 'Medium'},{'value': 'Bad'}]},{'data': [{'value': 'White'},{'value': 'Large'},{'value': 'Best'}]}]
let arr = data.reduce((arr, item) => { // look at each item in the data array
item.data.forEach(({value}, index) => { // look at each item in the item.data array
(arr[index] || (arr[index] = [])).push(value) // create and array if necessary and push value into it
})
return arr
},[])
console.log(arr)
这是我的问题的解决方案,使用主循环超过您想要读取的不同属性的数量,并在每个循环内部使用通过方法Array.from()提供的工具
let a = [
{'data': [
{'value': 'Red'},
{'value': 'Small'},
{'value': 'Good'}
]},
{'data': [
{'value': 'Black'},
{'value': 'Medium'},
{'value': 'Bad'}
]},
{'data': [
{'value': 'White'},
{'value': 'Large'},
{'value': 'Best'}
]}
];
// The new array.
let newArr = [];
// Number of properties for each "data" object.
let keys = 3;
for (let k = 0; k < keys; k++)
{
newArr.push(Array.from(a, (v) => {
return v.data[k].value;
}));
}
console.log(newArr);
或者,您可以用Array.from()
替换map(),如下所示:
for (let k = 0; k < keys; k++)
{
newArr.push(a.map((v) => {
return v.data[k].value;
}));
}
您也可以尝试以下示例显示。
filter()方法基本上是在我们想要基于某些条件的过滤输出时使用的。
var a = [
{
'data': [
{
'value': 'Red'
},
{
'value': 'Small'
},
{
'value': 'Good'
}
]
},
{
'data': [
{
'value': 'Black'
},
{
'value': 'Medium'
},
{
'value': 'Bad'
}
]
},
{
'data': [
{
'value': 'White'
},
{
'value': 'Large'
},
{
'value': 'Best'
}
]
}
]
var obj = {};
for(var o of a) {
for(var i in o.data) {
if(obj[i] === undefined) {
obj[i] = [o.data[i].value];
} else {
obj[i].push(o.data[i].value);
}
}
}
console. log(obj);
/*
{ '0': [ 'Red', 'Black', 'White' ],
'1': [ 'Small', 'Medium', 'Large' ],
'2': [ 'Good', 'Bad', 'Best' ] }
*/
var array = [
{
'data': [
{
'value': 'Red'
},
{
'value': 'Small'
},
{
'value': 'Good'
}
]
},
{
'data': [
{
'value': 'Black'
},
{
'value': 'Medium'
},
{
'value': 'Bad'
}
]
},
{
'data': [
{
'value': 'White'
},
{
'value': 'Large'
},
{
'value': 'Best'
}
]
}
]
var res = [];
for(var i in array)
{
var subData = array[i]['data'];
var tmp = [];
for(var j in subData)
tmp.push(subData[j]['value']);
res.push(tmp);
}
console.log(res);