As mentioned in the other answers, the issue is that you're changing an existing object every iteration instead of adding a new one.
I'd like to add that that you can also use reduce instead (I personally prefer the syntax and it's a bit shorter):
let nums = [{id:1, first_name: "sade", last_name: "Smith"}, {id:2, first_name: "Jon", last_name: "Doe"}];
let em = [];
let num2 = {id:null, name: ""}
em = nums.reduce((accumulator, item) => {
accumulator.push({
id: item.id,
name: `${item.first_name} ${item.last_name}`;
})
}, [])
More info about the reduce function can be found in the MDN docs.
Why does it work like this?
If you want to know more about why your solution didn't work, it's important to understand that in JS there's a difference between primitive values and objects.
By assigning a variable that contains an object to another variable, you are not assigning a new object, but only pointing to an existing one instead. This causes coupling between your objects, they are pointing to the same object, as can be demonstrated here:
var obj1 = {name: 'Sherlock Holmes', country: 'England'}
var obj2 = obj1;
obj2.country = 'US';
console.log(obj1.country) // US
console.log(obj2.country) // US
Because of this, when you want to assign an object to another variable you need to clone its content, but create a new object, therefor the variable will point to a new object and not to the old one.
There are many ways to do it, but few simple ones are:
- Using the spread operator like this:
var obj1 = {name: 'Sherlock Holmes', country: 'England'}
var obj2 = { ...obj1 };
obj2.country = 'US';
console.log(obj1.country) // England
console.log(obj2.country) // US
- Stringifying then parsing using
JSON.stringify and JSON.parse
var obj1 = {name: 'Sherlock Holmes', country: 'England'}
var obj2 = JSON.parse(JSON.stringify(obj1));
obj2.country = 'US';
console.log(obj1.country) // US
console.log(obj2.country) // US
There are more ways, and differences between those ways, if your object has nested objects as well, the replications might not occur correctly, at this point it's best to use a function that does the cloning for you, like lodash's deepClone function.
num2, its the same object. Clone num2 then push