0

Given arrays name ['a','b','c'] data [1 , 2 , 3]

I want the result [{name: 'a', data: 1}, {name: 'b', data: 2}, {name: 'c', data: 3}],

I could do

 let combinedData = [];
 for (let i = 0; i < data.length; i++) {
     combinedData.push({name: name[i], data: data[i]});
 }

but I am looking for an elegant way, shot. (Using external lib is acceptable e.g. lodash)

3 Answers 3

2

You can use Array.map:

let name = ['a','b','c'];
let data = [1,2,3];
let combined = name.map((v, i) => ({name: v, data: data[i]}));
console.log(combined);

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

Comments

1

A simple es6 solution could be:

let arr1 = ...;
let arr2 = ...;

let data = arr1.map((item, i) => ({a: item, b: arr2[i]}));

2 Comments

That's not a valid arrow function resulting in a SyntaxError.
Yes, you're right. I've missed the parentheses around the object.
1
let combinedData ={};
  let name = ['a','b','c'];
    let data = [1 , 2 , 3];
 for (let i = 0; i < data.length; i++) {
     combinedData[name[i]]=data[i];
 }
 console.log(combinedData);

1 Comment

I was looking for "[{name: 'a', data: 1}, {name: 'b', data: 2}, {name: 'c', data: 3}]", not {a: 1, b: 2, c: 3}, thanks anyways :)

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.