如何从一个包含数组对象的数组中获取特定属性?

5

我有一个由数组组成的数组,每个数组包含对象。以下是我参考的简化版本(这是我原始数组的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.

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


您能展示一下示例输出吗? - Koushik Chatterjee
请提供一个 [mcve],其中包含一些示例数据,展示您正在处理什么以及您期望的结果是什么。 - Heretic Monkey
8个回答

11

扁平化它,并将其映射到名称或反之亦然

首先扁平化它,然后映射

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来代替外部的映射,并将其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);


3

/* TEST DATA */
array1 = [
  { name: 'test1', score: 40, date: '2018-09-18T00:00:00.000Z' },
];
array2 = [
  { name: 'test4', score: 50, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test5', score: 40, date: '2018-09-18T00:00:00.000Z' }, 
];
array3 = [
  { name: 'test6', score: 50, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test7', score: 50, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test8', score: 40, date: '2018-09-18T00:00:00.000Z' },
  { name: 'test9', score: 50, date: '2018-09-18T00:00:00.000Z' },
];

testResults = [array1, array2, array3];

// Solution 

function getListOfName(){
  let names = [];
  testResults.map(testResult => {
    testResult.map(({name}) => {if(name) names.push(name)})
  })
  return names;
}
console.log("Full list of names", getListOfName());

// If you want to restrict to K names from each array
function getFirstKNamesfromArray(limit){
  let names = [];
  testResults.map(testResult => {
    testResult.map(({name}, index) => {
      if(name && (index < limit)) names.push(name)
    })
  })
  return names
}
console.log("First 2 names from each array", getFirstKNamesfromArray(2));


谢谢。正是我想要的。 - 221b
很高兴能为您服务 :-) - Mohammed Ashfaq
只是好奇 - 是否有办法仅获取每个数组对象的前两个“name”值? - 221b
1
@221 testResults.map(testResult => { testResult.map((test, index) => { if(index<2)names.push(test.name) }) }) - Mohammed Ashfaq

2

需要注意的是map返回一个数组,您需要对其进行迭代。filter或reduce也可以达到相同的效果。

const test1= array1.map(x=> x.values) // x doesn't have a property named  "value"
//simply use forEach
array1.forEach((el) => console.log(el.name))

如果您想捕获集合中的名称:

const let container = [];
array1.forEach((el) => container.push(el.name))

理解迭代器函数的好方法是先使用循环,然后尝试将您的代码“翻译”成其中之一。

1
因为在你的第一个地图中,x是一个数组,而不是一个对象。所以,没有value。你应该映射内部数组,然后获取所需的值。

const arr = [
  [
    {
      name: "test",
      score: 40,
      date: "2018-09-18T00:00:00.000Z"
    },
    { name: "test2", score: 50, date: "2018-09-18T00:00:00.000Z" }
  ],
  [
    {
      name: "foo",
      score: 40,
      date: "2018-09-18T00:00:00.000Z"
    },
    { name: "bar", score: 50, date: "2018-09-18T00:00:00.000Z" }
  ]
];

const test1 = arr
  .map(x => x.map(y => y.name))
  .reduce((acc, el) => [...acc, ...el], []);


console.log(test1);


0

这里:

const arr = [
    [{name: 'a', date:'x'}, {name: 'b', date:'y'}],
    [{name: 'c', date:'x'}, {name: 'd', date:'y'}]
];

const names = arr.map(el => el.map(obj => obj.name));

console.log(names.join());
console.log(names.flat());

你可以使用 flat() 将名称保留在数组中,或使用 join() 将名称合并为字符串。

0
<b>const test1= array1.map(x=> x.values)</b>

这个返回未定义。

let requiredArr = [];

let array1 = [Array(2), Array(3), Array(2)]

let test2 = array1.map(x => x.map(y => requiredArr(y.name));

test2将会得到期望的结果。


0

这应该可以正常工作。您需要展平数组结构并映射名称。

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

const names = array.reduce((acc, innerArray) => {
  return [...acc, ...innerArray.map(entry => entry.name)]
}, [])

console.log(names)


0

在Koushik的示例基础上,使用ES2019,您可以使用flat()来展平嵌套数组:

const array = [[{name: 'test1'}, {name: 'test2'}], [{name: 'test3'}, {name: 'test4'}]]
var res = array.flat().map( ({name}) => name );
console.log(res);

或者如果您有更深层次的:

const array = [[[{name: 'test1'}], {name: 'test2'}], [{name: 'test3'}, {name: 'test4'}]]
var res = array.flat(2).map( ({name}) => name );
console.log(res);

等等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接