繁体   English   中英

如何在 JavaScript 中从 object 嵌套道具返回一个新的 object 数组

[英]How to return a new array of object from object nested props with reduce in JavaScript

我正在尝试从另一个object的嵌套属性中返回一个新的objects array 这是我当前的object

const teams = {
  GRYFFINDOR: {
    display: 'Gryffindor',
    channel: ['#team-gryffindor'],
    ui: 'lion',
  },
  HUFFLEPLUFF: {
    display: 'Hufflepuff',
    channel: ['#team-hufflepuff'],
    ui: '', // empty string on purpose
  },
  SLYTHERIN: {
    display: 'Slytherin',
    channel: ['#team-slytherin'],
    ui: 'snake',
  },
}

现在,我正在尝试返回一个objects array ,如下所示:

[
  { value: 'lion' },
  { value: '' },
  { value: 'snake' },
]

这是我尝试过的:

const teamsUI = [Object.keys(teams).reduce((carry, item) => {
  return {...carry, ...{ ['value']: teams[item].ui  }}
}, {})];;

但是,我明白了:

console.log(teamsUI); // returns [ { value: 'snake' }]

我究竟做错了什么?

除了嵌套结果结构之外,您还可以获取值并解构想要的属性格式。

 const teams = { GRYFFINDOR: { display: 'Gryffindor', channel: ['#team-gryffindor'], ui: 'lion' }, HUFFLEPLUFF: { display: 'Hufflepuff', channel: ['#team-hufflepuff'], ui: '' }, SLYTHERIN: { display: 'Slytherin', channel: ['#team-slytherin'], ui: 'snake' } }, result = Object.values(teams).map(({ ui: value }) => ({ value })); console.log(result);

你可以这样做:

 const teams = { GRYFFINDOR: { display: 'Gryffindor', channel: ['#team-gryffindor'], ui: 'lion', }, HUFFLEPLUFF: { display: 'Hufflepuff', channel: ['#team-hufflepuff'], ui: '', // empty string on purpose }, SLYTHERIN: { display: 'Slytherin', channel: ['#team-slytherin'], ui: 'snake', }, } const result = Object.values(teams).map(({ ui }) => ({ value: ui })); console.log(result);

这是实现您想要的最短的方法

Object.keys(teams).map(t=>({value: teams[t].ui}))

现在你做错了什么?

看看这部分

Object.keys(teams).reduce((carry, item) => {
  return {...carry, ...{ ['value']: teams[item].ui  }}
}, {});

您正在将 object 减少为具有相同键的单个值,称为value This means that the value of teams[item].ui of the current object in the reduce function will override the previous and hence you'll end up with the last object of that reduce function. 您终于将最后一个 object 包装在一个数组中,从而为您提供您所拥有的。

实现这一目标的更好方法是做这样的事情

Object.keys(teams).reduce((carry, item, index)=>{
  carry[index] = { value: teams[item].ui };
  return carry;
}, []);

暂无
暂无

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

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