请参阅此处的 jsfiddle:https://jsfiddle.net/remenyLx/2/
我的数据包含对象,每个对象都有图像数组。我只想要每个对象的第一张图像。
var data1 = [
{
id: 1,
images: [
{ name: '1a' },
{ name: '1b' }
]
},
{
id: 2,
images: [
{ name: '2a' },
{ name: '2b' }
]
},
{
id: 3
},
{
id: 4,
images: []
}
];
var filtered = [];
var b = data1.forEach((element, index, array) => {
if(element.images && element.images.length)
filtered.push(element.images[0].name);
});
console.log(filtered);
输出需要平坦:
['1a', '2a']
如何让这个更漂亮?
我对 JS map
、reduce
和 filter
不太熟悉,我认为这些会让我的代码更合理; forEach
感觉没有必要。
最佳答案
首先你可以filter输出没有正确 images
属性的元素,然后 map它到新数组:
const filtered = data1
.filter(e => e.images && e.images.length)
.map(e => e.images[0].name)
要在一个循环中执行此操作,您可以使用 reduce功能:
const filtered = data1.reduce((r, e) => {
if (e.images && e.images.length) {
r.push(e.images[0].name)
}
return r
}, [])
关于javascript - 通过迭代 JSON 对象创建新数组并仅获取其内部数组的 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387950/