0

I have the following object and list:

myObj = [
          { width: 10, height: 15, length: 20 },
          { width: 8, height: 10, length: 10 },
          { width: 23, height: 5, length: 5 },
          { width: 11, height: 18, length: 10 }
        ];
heights = {12,13,14,15};

In Javascript or jQuery what is the best way to replace the object heights with the values in the heights list? The order does matter. Results should be:

 myObj = [
              { width: 10, height: 12, length: 20 },
              { width: 8, height: 13, length: 10 },
              { width: 23, height: 14, length: 5 },
              { width: 11, height: 15, length: 10 }
            ];
2
  • 1
    That is the wrong way to make an array. It should be heights = [12, 13, 14, 15] Commented Oct 10, 2014 at 2:31
  • It should definitely be an array. Your current code gives a syntax error. Commented Oct 10, 2014 at 2:32

1 Answer 1

1

You need to loop, and assign the values

var myObj = [{
    width: 10,
    height: 15,
    length: 20
}, {
    width: 8,
    height: 10,
    length: 10
}, {
    width: 23,
    height: 5,
    length: 5
}, {
    width: 11,
    height: 18,
    length: 10
}];
var heights = [12, 13, 14, 15];

myObj.forEach( function(obj,i){
    obj.height = heights[i]
});
console.log(myObj)

document.getElementById('log').innerHTML = JSON.stringify(myObj)
<div id="log"></div>

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

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.