0

I have two array. I want to merge this two arrays into one array. One array consisting keys and another one values.My array looks like

productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
    "8": 5,
    "7": 1,
    "9": 3
}

I already tried to merge these arrays, in this way

var newArray = {};
for(var i=0; i< productId.length; i++){
  newArray[productId[i]] = quantity [i];
}
console.log(newArray);

It returns

Object [ <7 empty slots>, "5", "1", "3" ]
8
  • 1
    Your code works fine, please share a working fiddle or snippet to demonstrate/replicate your issue. Commented Jan 8, 2018 at 6:05
  • You seems like creating array of objects instead of Array Commented Jan 8, 2018 at 6:07
  • @AuxTaco Which browser? Commented Jan 8, 2018 at 6:30
  • Mozila Firefox and Google chrome booth Commented Jan 8, 2018 at 6:33
  • 1
    @AuxTaco Yup was about to delete my comments. Sourabh just linked a questions that highlights the bug of FF. Commented Jan 8, 2018 at 6:37

3 Answers 3

0

You are working in firefox so you may get this type of issue because the problem might be caused at how Firefox' console.log has interpreted the input object.

Please look here

Empty slots in JavaScript objects?

Try this

var productId = [8,7,9];
var quantity = ["5","1","3"];
var newarray = {};
productId.forEach((key, i) => newarray[key] = quantity[i]);
console.log(newarray);

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

5 Comments

Please specify what's wrong with OP's code as well. Why your code works and OP's doesn't?
@Rajesh Hey this is the problem in Firefox
I have Updated my answer where you will find link look into that
Thanks! Being a chrome user, I was not aware about it.
@Rajesh Welcome bro :)
0

Try the following:

var productId = [8,7,9];//Key Element
var quantity = ["5","1","3"];//Value Element

var obj = {};
var i = 0;
for(var k of productId) {
    obj[k] = parseInt(quantity[i]);
    i++;
}
console.log(obj);

3 Comments

Also, this is a very bad implementation of .map. You are updating an object and returning in map. and the you use [0] for display purpose. This is just wrong
still it returns [<7 empty slots>, "5", "1"."3" ]
@Rajesh no it was not intended for you
0

Your new "array" is not an Array but an Object.

You can iterate on one of the arrays using Array.reduce to construct the object.

Something like that:

const arr1 = ['8', '2', '4'];
const arr2 = ['28', '12', '45'];

const result = arr1.reduce((obj, currentItem, index) => {
  obj[currentItem] = arr2[index];
  return obj;
}, {});

console.log(result);

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.