简体   繁体   English

Map Angular 阵列到 Object

[英]Map Angular Array to Object

I have been looking and have found a few good references for transforming arrays to objects, but I can't seem to find my use case.我一直在寻找并找到了一些将 arrays 转换为对象的好参考,但我似乎找不到我的用例。 I have an array with the following format我有一个具有以下格式的数组

[
  {id: 1, name: 'hello', display: false},
  {id: 5, name: 'hello2', display: true},
  {id: 7, name: 'hello8', display: true},
]

and I would like to map it into something like this我想把 map 变成这样的东西

{
  5: {id: 5, name: 'hello2'},
  7: {id: 7, name: 'hello8'}
}

I have been trying to use the map function, but I can't figure it out since I want the keys of my map to be an id.我一直在尝试使用 map function,但我无法弄清楚,因为我希望我的 map 的密钥是一个 id。 This is what I have so far but it is obviously wrong.这是我到目前为止所拥有的,但这显然是错误的。

const myArray = [
  {id: 1, name: 'hello', display: false},
  {id: 5, name: 'hello2', display: true},
  {id: 7, name: 'hello8', display: true},
];

const myMap = myArray.filter(row => row.display)
                     .map(row => {
                         return {row.id: {id: row.id, name: row.name}
                     });

Filter the array, map it to pairs of [id, obj] , and convert to an object using Object.fromEntries() .过滤数组,map 将其转换为[id, obj]对,并使用Object.fromEntries()转换为 object。 You can use destructuring and rest syntax ( ... ) to remove display .您可以使用解构和 rest 语法 ( ... ) 来删除display

Notes: if Object.fromEntries() is not supported, change target in TS Config to ES2019 .注意:如果不支持Object.fromEntries() ,请将 TS Config 中的target更改为ES2019

 const arr = [{id: 1, name: 'hello', display: false},{id: 5, name: 'hello2', display: true}, {id: 7, name: 'hello8', display: true}] const result = Object.fromEntries( arr.filter(o => o.display).map(({ display, ...o }) => [o.id, o]) ) console.log(result)

Another option is to use Array.reduce() to create the object.另一种选择是使用Array.reduce()创建 object。 In that case, you can skip objects with false display .在这种情况下,您可以跳过具有错误display的对象。

 const arr = [{id: 1, name: 'hello', display: false},{id: 5, name: 'hello2', display: true}, {id: 7, name: 'hello8', display: true}] const result = arr.reduce((acc, { display, ...o }) => { if(display) acc[o.id] = [o.id, o] return acc }, {}) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM