3

I have 2 separate array but both of them have same length. How to merge them together into an array object so that it's easy to populate later?

for example

[1,2,3,4,5]
['a','b','c','d','e']

I expect I can have something like

[{'index':1,'value':'a'},{'index':2,'value':'b'}]

I've tried

    $.each(a, function(i,x){

      $.each(b, function(i,z){
        c['index'] = x;
        c['value'] = z;
      });

    });

But I got only [{'index':'1','value':'a'}]

2 Answers 2

2

You can use map() for iterate and generate the new array

var arr1 = [1, 2, 3, 4, 5],
  arr2 = ['a', 'b', 'c', 'd', 'e'];

var res = arr1.map(function(v, i) {
  return {
    index: v,
    value: arr2[i]
  };
})

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

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

Comments

1

With ES6 you can do it with arrow function like below:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = ["a", "b", "c", "d", "e"];

const output = arr1.map((el, i) => ({ index: el, value: arr2[i] }));

console.log(output);

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.