我在这里有一个问题,我想让value
数组中的所有values
都在该数组中。
const sample = [
{
"key": "sampleKey", "values":
[
{ "key": "insidesampleKey", "value": 2 },
{ "key": "insideofinside", "value": 2 }
]
},
{
"key": "sampleKey2", "values":
[
{ "key": "insideSampleKey2", "value": 1 }
]
},
{
"key": "samplkey3", "values":
[
{ "key": "insideofsampleKey3", "value": 1 }
]
}
]
到目前为止,我只能打印第一个console.log(sample[0].values[0].value)
。感谢您的帮助。非常感谢,并度过了一个愉快的周末
答案 0 :(得分:1)
您可以使用reduce
和concat
获得平坦的单个阵列。
const sample = [{"key":"sampleKey","values":
[{"key":"insidesampleKey","value":2},{"key":"insideofinside","value":2}]},
{"key":"sampleKey2","values":[{"key":"insideSampleKey2","value":1}]},
{"key":"samplkey3","values":[{"key":"insideofsampleKey3","value":1}]}]
var values = sample.reduce((acc, item) => acc.concat(item.values.map(v=> v.value)),[]);
console.log(values);
答案 1 :(得分:1)
我认为flatMap可能是解决此问题的最佳方法。
sample.flatMap(outer => external.values.map(inner => inner.value))
答案 2 :(得分:0)
最简单的方法是在数组上使用flatMap,如下所示。您可以将polyfill用于尚不支持的浏览器。使用MDN了解更多信息。
sample.flatMap(item => item.values.map(inner => inner.value))
答案 3 :(得分:0)
如果要打印其他value
属性,只需在数组上map
,然后查看values
数组,然后查看value
,最后使用flat
获得单个数组:
const sample = [{
"key": "sampleKey",
"values": [{
"key": "insidesampleKey",
"value": 2
}, {
"key": "insideofinside",
"value": 2
}]
},
{
"key": "sampleKey2",
"values": [{
"key": "insideSampleKey2",
"value": 1
}]
},
{
"key": "samplkey3",
"values": [{
"key": "insideofsampleKey3",
"value": 1
}]
}
];
console.log(sample.map(e => e.values.map(x => x.value)).flat(1));