2

Suppose I have this data:

var id = 81;
var categories = [1, 2, 3, 4, 5];

How do I transform this into:

[{id: 81, category: 1}, {id: 81, category: 2}, {id: 81, category: 3}, {id: 81, category: 4}, {id: 81, category: 5}]

Is there an elegant way to do this using underscore or lodash?

4 Answers 4

9

No need for libraries here.

const result = categories.map(x => ({ id, category: x }))
Sign up to request clarification or add additional context in comments.

Comments

2

Working Example JSBin

var id = 81;
var categories = [1, 2, 3, 4, 5];
var arr = [];

for (var i = 0; i < categories.length; i++) {
  arr.push({id: id, category: categories[i]});
}

Or:

var a = categories.map(function(a) {
  return {id: id, category: a};
});

Comments

1

You don't need any library, just good, old Vanilla JS.

var newArray = categories.map(function(item) {
  return {id: id, cetegory: item}
});

1 Comment

The irony: Vanilla.js is a library, a 0 byte library.
1

Using Lo-Dash/Underscore, the code would be:

var result = _.map(categories, x => ({ id, category: x }));

But this is actually longer than the pure JS solution (from Роман Парадеев):

var result = categories.map(x => ({ id, category: x }));

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.