I need to create a new object and push it into an array of objects. When i try the code below it instead results in an integer which is the value of the array length.
const newThing = Object.assign(
{},
{
__typename: 'Group',
id: groupId,
},
);
// userGroups is an array of strings eg ['1', '2']
const newUserGroups = userGroups
.map(item => {
return Object.assign({}, { __typename: 'Group' }, { id: item });
})
.push( newThing );
console.log(newUserGroups);
You could use Array#concat
, because Array#push
returns the new length of the array and concat returns a new array.
const newUserGroups = userGroups
.map(item => {
return Object.assign({}, { __typename: 'Group' }, { id: item });
})
.concat(newThing);
You are miss-implementing the chaining.
currently your chain is like this:
x = array.map().push()
so x
will get the returned value of the last chained method ( push
)
And push
return the length of the array, not the array itself.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Remove the chain and it will be ok:
const newThing = Object.assign({}, { __typename: 'Group', id: 'groupId', }, ); // userGroups is an array of strings eg ['1', '2'] const userGroups = ['1', '2']; const newUserGroups = userGroups .map(item => { return Object.assign({}, { __typename: 'Group' }, { id: item }); }); newUserGroups.push(newThing); console.log(newUserGroups);
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.