简体   繁体   中英

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.

So to use the map you'd still get undefined values. You probably would want to use reduce and do the following.

 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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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