简体   繁体   中英

How to array after object in Nodejs

I have array but i need to join object after array

my array

const users = [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ]

my object

{ street: true }

result i need

[
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ], { street: true }

If you want to join then up like an array you can do

const newArray = [users, { street: true }]

Otherwise if you want to join them up as a new object do

const newObject = {
  residents: users,
  info: { 
    street: true
  }
}

like @AT-martins suggested

so you need an object with 2 properties, one could be called "residents" and the other "info", the structure would look like this:

{
 residents: [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
  ],
  info: { 
    street: true
  }
}

I think this is the easiest way to have your array and your object in one single data structure.

Simply use push() for this. So you have this array:

const users = [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ]

And you want to attach this:

const anotherObj = { street: true };

Then you can use this:

const users = [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ];
const anotherObj = { street: true };
users.push(anotherObj);

This will do the job, But. the above is the solution if you want that object to go inside the array, If you want to make a new array: you can do this:

const arr = [users, anotherObj]

This will make a new array with the users array in index 0 and the obj at index 1

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