Home > OS >  Circular Referenced Objects Javascript
Circular Referenced Objects Javascript

Time:01-27

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.

CodePudding user response:

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);

CodePudding user response:

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