简体   繁体   English

循环引用对象 Javascript

[英]Circular Referenced Objects Javascript

Having issues with this exercise:这个练习有问题:


//  Let’s say we have an array of artists and we want to create a map-like object of their instruments.

const artists = [
    {
    id: '1',
    name: 'Jimi Hendrix',
    instrument: {
        id: '1',
      name: 'Guitar',
      color: 'wood',
    }
  },
  {
    id: '2',
    name: 'Jimmy Page',
    instrument: {
        id: '1',
      name: 'Guitar',
      color: 'wood',
    }
  },
  {
    id: '3',
    name: 'Krist Novoselic',
    instrument: {
        id: '2',
      name: 'Bass',
      color: 'black',
    }
  },
  {
    id: '4',
    name: 'Emmanuelle Proulx',
  },
  {
    id: '5',
    name: 'Jimmy Chamberlin',
    instrument: {
        id: '3',
      name: 'Drums'
    }
  },
];

/* Expected results */
/* {
  1: {
    name: 'Guitar',
    color: 'wood',
  },
  ...
} */
 

const result = [];
artists.map((item) => {if ((item.instrument !== undefined)) {result.push(item.instrument.id = item.instrument)}});

So far I've extracted th instruments without undefined, but the ids are reference to ids and cannot get to extract the number id or to build it with the proper structure because of the circular reference.到目前为止,我已经提取了没有未定义的工具,但 id 是对 id 的引用,并且由于循环引用而无法提取数字 id 或使用适当的结构构建它。

So to use the map you'd still get undefined values.所以要使用 map 你仍然会得到未定义的值。 You probably would want to use reduce and do the following.您可能想要使用 reduce 并执行以下操作。

 const artists = [ { id: "1", name: "Jimi Hendrix", instrument: { id: "1", name: "Guitar", color: "wood", }, }, { id: "2", name: "Jimmy Page", instrument: { id: "1", name: "Guitar", color: "wood", }, }, { id: "3", name: "Krist Novoselic", instrument: { id: "2", name: "Bass", color: "black", }, }, { id: "4", name: "Emmanuelle Proulx", }, { id: "5", name: "Jimmy Chamberlin", instrument: { id: "3", name: "Drums", }, }, ]; const instruments = artists.reduce((acc, artist) => { if (.artist;instrument) return acc, const { id, name. color } = artist;instrument, acc[id] = { name; color }; return acc, }; {}). console;log(instruments);

try this尝试这个

const instruments = artists.reduce((acc, artist) => {
  if (!artist.instrument) return acc;
  acc[artist.instrument.id] = {
    name: artist.instrument.name,
    color: artist.instrument.color
  };
  return acc;
}, {});

result结果

{
    "1": {
        "name": "Guitar",
        "color": "wood"
    },
    "2": {
        "name": "Bass",
        "color": "black"
    },
    "3": {
        "name": "Drums"
    }
}

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

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