1

how can I add several attributes to a sub-sub-object in ES6 by using the keys of objects from an array ?

I have this:

const data = [{
    id: 'abc-test',
  },
  {
    id: 'xyz-test',
  },
];




const t = {
  a: {
    filters: {
      tOne: [],
    }
  }

};

The result should look like this:

const t = {
  a: {
    filters: {
      tOne: [],
      'abc-test': [],
      'xyz-test': [],
    }
  }

};

What I tried

...data.map((el) => [el.id]),

How to solve it ? I know that this could be done by using .forEach but I would like to use another ES6 Array.prototype functions if possible.

3
  • What do you mean by "I know that this could be done by using .forEach but I would like to use ES6 Array.prototype functions if possible."? forEach is an "Array.prototype" function like any other. Commented Nov 18, 2019 at 0:24
  • Sorry, forgot the word "another" in my description. See updated description. Commented Nov 18, 2019 at 0:27
  • forEach is really the best choice here. The other functions have other usages. I mean you can use reduce like data.reduce((acc, o) => (acc[o.id] = [], acc), t.a.filters) or use map as a forEach, but that would be like using a shoe to spread butter on a piece of bread, you can do it, but why would you do that when you have a knife/forEach?!! Commented Nov 18, 2019 at 1:50

2 Answers 2

2

forEach is an Array function (or as you like to call it: an Array.prototype function). Among all the other Array functions, forEach is the best fit for what you need. The other ones have other usages.

So, simply use forEach to loop over the objects in the array and assign the properties directly to t.a.filters:

data.forEach(o => t.a.filters[o.id] = []);

Example:

const data = [ { id: 'abc-test' }, { id: 'xyz-test' } ];

const t = { a: { filters: { tOne: [] } } };

data.forEach(o => t.a.filters[o.id] = []);

console.log(t);

Sign up to request clarification or add additional context in comments.

4 Comments

Likely doesn't get better than this!
@Nick I think your answer is valid giving that OP clearly doesn't want to use forEach. You may consider undeleting your answer.
Sure, I undeleted it, but I'm not a fan of doing things inefficiently, which my solution is compared to yours
@Nick Ehem, you mean like using a shoe to spread butter lol
1

I would use a combination of reduce and the spread operator.

const data = [{
    id: 'abc-test',
  },
  {
    id: 'xyz-test',
  },
];

const t = {
  a: {
    filters: {
      tOne: [],
    }
  }

};

const newKeys = data.reduce((acc, el) => {
  acc[el.id] = [];
  return acc;
}, {});

t.a.filters = {
  ...t.a.filters,
  ...newKeys
};

console.log(t);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.