0

I want to create Object-type array,for loop only push last value??

  var arr=[];
  var k={};
  k.num=0;
  k.name='';
  a=[1,2,3,4];
  b=['tom','sun','bob','kiki'];
  for(i=0;i<4;i++)
  {
      k.num=a[i];
      k.name=b[i];
      arr.push(k)
  }
  console.log(arr)
  
  //result [{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4}]

result:

2
  • You're pushing the same object reference 4 times and changing the value of its properties each iteration. Move the creation of the object inside the for loop and it'll work. Commented Feb 17, 2017 at 18:25
  • Possible duplicate of creating array object on each loop Commented Feb 17, 2017 at 18:29

1 Answer 1

1

Description

Added via comments in code

var arr = [];
// removed object declaration
// removed initialization
a = [1, 2, 3, 4];
b = ['tom', 'sun', 'bob', 'kiki'];
for (var i = 0; i < 4; i++) {
  // initialize new object
  var k = {};
  // set properties
  k.num = a[i];
  k.name = b[i];
  arr.push(k)
}
console.log(arr)

//result [{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4}]

Another way

var arr = [];
a = [1, 2, 3, 4];
b = ['tom', 'sun', 'bob', 'kiki'];
for (var i = 0, length = a.length; i < length; i++) {
  arr.push({num: a[i], name: b[i]})
}
console.log(arr)

//result [{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4}]

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.