-1

I have a list of objects (called this.listOfDesserts):

enter image description here

Each object (this.listOfDesserts) containing the following:

enter image description here

I also have a variable called this.relevantColumns which is dynamically generated though a line of code like so:

this.relevantColumns = this.listOfCakes.summaryCakes.numberOfUsers;

The end result is always an array. As an example it could equal something like ['1305','1306']

How can I generate a list from this.listOfDesserts of all objects where the index (In the 2nd image I believe it's represented by the purple e.g. 1304,1305,1306,1307,1308,header,id) is equal to the values of an array (this.relevantColumns)?

In this example how would I be able to get a list of all objects in this.listOfDessert with indexes 1305 and 1306 without hardcoding?

Everything is written dynamically so I can't really use hardcoded lines like this.variableName[1304].

Beginner_Hello
  • 357
  • 6
  • 19
  • 1
    This looks very similar to [this question](https://stackoverflow.com/questions/64452333/how-to-get-a-list-of-objects-by-their-id-using-an-array-of-numbers/64452394#64452394). That was a list of animals instead of desserts, but otherwise the same problem. – Barmar Oct 20 '20 at 21:16
  • 1
    Remove all images and put some data, this help to achieve a good the answer. – gillall Oct 20 '20 at 21:26
  • It's a similar problem but having tried the selected solution it only resulted in [undefined, undefined, __ob__: Observer] – Beginner_Hello Oct 20 '20 at 21:36

1 Answers1

0

There are two stages.

One, obtain a complete dictionary of all the values

listOfDesserts = [{ 1: {obj: 1}, 2: {obj: 2}} , {3: {obj: 3}}]
listOfDessertsFlattened = Object.assign({}, ...listOfDesserts) // { '1': { obj: 1 }, '2': { obj: 2 }, '3': { obj: 3 } }

Two, map over the relevant columns and get the result from the array:

listOfDessertsFlattened = { 1: {obj: 1}, 2: {obj: 2}, 3: {obj: 3}};
relevantColumns = [1, 3];
result = relevantColumns.map((columnName) => listOfDessertsFlattened[columnName]) //[ { obj: 1 }, { obj: 3 } ]
Jencel
  • 722
  • 7
  • 17
  • I've attempted to use result = relevantColumns.map((n) =>listOfDessertsFlattened[n]) however it led to [undefined, undefined, ob: Observer]. I believe it might be because it's an array of objects where each object holds multiple objects: [ 0: {1304: {},1305: {}, 1306: {}] etc.]. – Beginner_Hello Oct 20 '20 at 21:48
  • If it's hardcoded this seems to work: listOfDessertsFlattened[0][1304], is there a way I can do this dynamically? – Beginner_Hello Oct 20 '20 at 21:59