简体   繁体   中英

Javascript - Append array of object

I have this data

var game = [
  {
    'userType' : 'VIP',
    'data' : [{
      'name' : 'John'
    }]
  },
  {'userType' : 'VIP',
    'data' : [{
      'name' : 'Michelle'
    }]
  }];

var newArr = { isActive: true };

I've tried to do this

game.push.apply(game[0], newArr);

And there's no newArr when i did the console log

在此输入图像描述

Am I missing something here? How to append newArr to the first array of game? (game[0])

Thanks guys

You are adding properties of one object - newArr to another - game[0] and for that you can use Object.assign() .

 var game = [{ 'userType': 'VIP', 'data': [{ 'name': 'John' }] }, { 'userType': 'VIP', 'data': [{ 'name': 'Michelle' }] }]; var newArr = {isActive: true}; Object.assign(game[0], newArr); console.log(game) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM