gpt4 book ai didi

javascript - 如何从数组对象数组中获取特定属性?

转载 作者:行者123 更新时间:2023-11-30 07:31:12 27 4
gpt4 key购买 nike

我有一个数组的数组,每个数组都由对象组成。这是我所指内容的简化版本(它是我原始数组的 console.log)-

Array - [Array(2), Array(3), Array(2)]

每个数组都有以下格式的对象(从上面获取第一个数组)-

Array(2) - 
0: {name: "test", score:40, date: "2018-09-18T00:00:00.000Z"}
1: {name: "test2", score:50 date: "2018-09-18T00:00:00.000Z"}

其他数组类似,属性相同,值不同。

我正在尝试从每个对象中获取名称属性。我尝试了以下代码 - 但我最终得到了一个未定义的值:

const test1= array1.map(x=> x.values) // this gives me the array of arrays
const test2 = test1.map(function(y){return y.name})// this is my attempt to get the 'name' attribute from all of the arrays that include the objects.

我在这里错过了什么?有没有更好的方法使用箭头函数获取属性?

最佳答案

展平它,并将它映射到名称,或者反之亦然

首先展平它,然后映射

const array = [[{name: 'test1'}, {name: 'test2'}], [{name: 'test3'}, {name: 'test4'}]]

var res = [].concat(...array).map(({name})=>name);
console.log(res);

现在,将其映射到名称,然后展平

const array = [[{name: 'test1'}, {name: 'test2'}], [{name: 'test3'}, {name: 'test4'}]]

var res = [].concat(...array.map(a=>a.map(b=>b.name)))
console.log(res);

现在,在这一个中,您肯定会注意到我们实际上是在每个级别进行映射(我们必须这样做,只有第一个映射方法没有其他方法。所以我们可以在中执行 reduce外部 map 的位置和 concat 它本身,所以我们可以避免外部 concat (用于展平)和内部 concat 实际上会展平它。我们开始:

const array = [[{name: 'test1'}, {name: 'test2'}], [{name: 'test3'}, {name: 'test4'}]]

var res = array.reduce((r, a)=>r.concat(a.map(b=>b.name)), []);
console.log(res);

关于javascript - 如何从数组对象数组中获取特定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52390205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com