通过迭代JSON对象并只获取其内部数组的1来创建新数组
Create new array from iterating JSON objects and getting only 1 of its inner array
请在此处查看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
,我认为这些会使我的代码更明智;CCD_ 4感觉没有必要。
首先可以过滤掉没有正确images
属性的元素,然后将其映射到新数组:
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
}, [])
您可以使用reduce()
返回此结果。
var data1 = [{
id: 1,
images: [{
name: '1a'
}, {
name: '1b'
}]
}, {
id: 2,
images: [{
name: '2a'
}, {
name: '2b'
}]
}, {
id: 3
}, {
id: 4,
images: []
}];
var result = data1.reduce(function(r, e) {
if (e.hasOwnProperty('images') && e.images.length) r.push(e.images[0].name);
return r;
}, [])
console.log(result);
所有答案都在投影最终结果之前创建新数组:(filter
和map
各创建一个新数组(,所以基本上是创建两次。
另一种方法是仅产生预期值:
使用迭代器函数
function* foo(g)
{
for (let i = 0; i < g.length; i++)
{
if (g[i]['images'] && g[i]["images"].length)
yield g[i]['images'][0]["name"];
}
}
var iterator = foo(data1) ;
var result = iterator.next();
while (!result.done)
{
console.log(result.value)
result = iterator.next();
}
这将不会创建任何额外的数组,并且只返回期望的值!
但是,如果您必须返回一个数组,而不是对实际值执行某些操作,那么请使用此处建议的其他解决方案。
https://jsfiddle.net/remenyLx/7/
相关文章:
- 从多维嵌套json数组创建下拉列表
- 为对象数组创建列表项
- 如何在cycle js中从JSON数组创建组件
- 使用数据数组创建多个类似组件
- 如何在 Angular JS 中从关联数组创建多个复选框
- 如何为给定数组创建跨度列表
- 如何在javascript中使用2个一维数组创建层次结构树
- 从数据对象数组创建折线图
- 从 javascript 数组创建一个 Jquery 数组
- Angular2从数组创建一个列表
- 使用JavaScript's Reduce从对象数组创建数组
- 如何从数组创建 jqtree
- 从字符串数组创建唯一组合数组
- 反应.js通过数组创建循环
- 从数组创建新元素,直到每秒数组为空
- 如何使用其他流的值数组创建流
- JavaScript:从字节数组创建图像资源
- 使用拆分字符串的数组创建一个对象
- 从一组数据或数组创建对象
- 多维数组 - 创建一个表