Hi there I am adding the string 'a ' to the beginning of the value of name. I have also added a condition where if the value of name.length === 3, then add the string 'a ' but it is only returning the objects that get changed and only the name property.
var values1 = [
{
name: 'dog',
surname: 'good',
skills: 'programming',
},
{
name: 'cat',
surname: 'soft',
skills: 'engineer',
},
{
name: 'elephant',
surname: 'big',
skills: 'programming',
},
];
let array = [];
for (let i = 0; i < values1.length; i++) {
if (values1[i]['name'].length == 3) {
array.push({ name: 'a ' + values1[i]['name'] });
}
}
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
This is the result I would like to return.
[
{
name: 'a dog',
surname: 'good',
skills: 'programming',
},
{
name: 'a cat',
surname: 'soft',
skills: 'engineer',
},
{
name: 'elephant',
surname: 'big',
skills: 'programming',
},
];
Here is an example using map() and destructuring the name property in the callback.
var values1 = [
{ name: 'dog', surname: 'good', skills: 'programming' },
{ name: 'cat', surname: 'soft', skills: 'engineer' },
{ name: 'elephant', surname: 'big', skills: 'programming' },
];
const result = values1.map(({ name, ...rest }) =>
({ name: (name.length === 3 ? `a ${name}` : name), ...rest }));
console.log(result);
But to make your code work you simply need to be sure to push the whole object regardless of whether the name is changed or not. Here creating a copy of the object using Object.assign() updating the name if needed, then pushing the copy to the array.
var values1 = [
{
name: 'dog',
surname: 'good',
skills: 'programming',
},
{
name: 'cat',
surname: 'soft',
skills: 'engineer',
},
{
name: 'elephant',
surname: 'big',
skills: 'programming',
},
];
let array = [];
for (let i = 0; i < values1.length; i++) {
const obj = Object.assign({}, values1[i]);
if (obj['name'].length === 3) {
obj.name = 'a ' + obj['name'];
}
array.push(obj);
}
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
You're quite close, but instead of adding a name key (push()) you want to reassign the value of the name field.
var values1 = [
{
name: 'dog',
surname: 'good',
skills: 'programming',
},
{
name: 'cat',
surname: 'soft',
skills: 'engineer',
},
{
name: 'elephant',
surname: 'big',
skills: 'programming',
},
];
for (let i = 0; i < values1.length; i++) {
if (values1[i]['name'].length == 3) {
values1[i]['name'] = 'a ' + values1[i]['name'];
}
}
console.log(values1)
I modified the existing array rather than adding a new one. I don't think it's dangerous as we are updating a primitive.