2

For example I have this arrays:

a = [1, 2, 3];
b = ["a", "b", "c"];

I want to make one object from these arrays that would look like this:

c = [{
  a: 1,
  b: "a"
},
{
  a: 2,
  b: "b"
},
{
  a: 3,
  b: "c"
}];
3
  • 4
    what did you try? Commented Jul 13, 2018 at 11:18
  • I made one empty array containing certain number of objects like this c = [{ a: 0, b: 0 },{ a: 0, b: 0 },{ a: 0, b: 0 }] and then with for loop i filed in data but this is really bad if I had 100+ arrays Commented Jul 13, 2018 at 11:21
  • 1
    Check Nikhil's answer Commented Jul 13, 2018 at 11:22

6 Answers 6

5

You can use Array.map

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

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

Comments

2

You can use Array#reduce to do something like this perhaps:

var a = [1, 2, 3];
var b = ["a", "b", "c"];

var c = a.reduce((accumulator, e, index) => {
  return accumulator.concat({a: e, b: b[index]});
}, [])

console.log(c);

Comments

1

You can use a for-loop like this:

    var a = [1, 2, 3];
    var b = ["a", "b", "c"];

    var c = [];

    for (var i = 0; i < a.length; i ++) {
        c[i] = {'a': a[i], 'b': b[i]};
    }
    console.log(c);

1 Comment

Thank you this solution is so simple and easy to understand for a beginner like me.
0

You can use Array.forEach() loop for that:

var a = [1, 2, 3];
var b = ["a", "b", "c"];
var c = [];
a.forEach((item, index)=>{
  c.push({a: item, b: b[index]});
});
console.log(c);

Comments

0

You could take an object with an arbitrary count of properties and generate an array of objects.

var a = [1, 2, 3],
    b = ["a", "b", "c"],
    result = Object
        .entries({ a, b })
        .reduce((r, [k, a]) => {
            a.forEach((v, i) => Object.assign(r[i] = r[i] || {}, { [k]: v }));
            return r;
        }, []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

Traditional but compatible way

Note: Most solutions in this page don't check if variables a and b have the same length

var a = [1, 2, 3];
var b = ["a", "b", "c"];

function combine(a,b){
        
    if (a.length === b.length){ // Check if both arrays have same length  
      var arr = []; // Make an empty array
      for(var i=0; i<a.length; i++){ // iterate every element of the array
          var obj = {} // Make an empty object
          obj["a"] = a[i];
          obj["b"] = b[i];
          arr.push(obj);
      }
    }else{        
        throw "Arrays don't have the same length";
    }
    
    return arr;
}

combine(a, b); // Use it like a function

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.