How to remove a property from array of objects [duplicate] - javascript

This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 1 year ago.
I have an array of objects with name and age property:
[
{ name: "Matthew", age: 23 },
{ name: "James", age: 20 },
{ name: "Daniel", age: 25 },
{ name: "Joshua", age: 22 }
]
I want to remove age property from all of the objects and print in console like
[
{ name: "Matthew" },
{ name: "James" },
{ name: "Daniel" },
{ name: "Joshua" }
]

Iterate over your array and use delete keyword.
let array = [
{ name: "Matthew", age: 23 },
{ name: "James", age: 20 },
{ name: "Daniel", age: 25 },
{ name: "Joshua", age: 22 }
]
array.forEach(function(v){ delete v.age });
console.log(array);

You can use map function to achieve this.
let output = test.map(({name}) => ({name}));
If you want to filter with multiple object you can add after name like {name, salary}
var test =[
{ name: "Matthew", age: 23 },
{ name: "James", age: 20 },
{ name: "Daniel", age: 25 },
{ name: "Joshua", age: 22 }
];
let output = test.map(({name}) => ({name}));
console.log(JSON.stringify(output, null, 2));

const newData = oldData.map(item=>({name:item.name}))

Related

Node Js - Mongo DB - Update Many

Here is an example database I have in mongodb.
[
{name: "Tommy", age: 12, _id: 12345 },
{name: "Pat", age: 22, _id: 54321 },
{name: "Bridie", age: 64, _id: 98765 }
]
How do I update the age of Pat to be 50 and the age of Tommy to be 20 in a single query using updateMany?
Im currently updating them individually in a for loop using this method.
const peopleToBeUpdated = [
{ name: "Pat", age: 50 },
{ name: "Tommy", age: 20 }
]
for (const person of peopleToBeUpdated) {
try {
await peopleSchema.updateOne({ name: person.name }, { $set: { age: person.age }})
} catch (error) {
}
}
Any help is appreciated, thanks..

Add "id" to the first in each object in an array (JavaScript) [duplicate]

This question already has answers here:
Is there a way to sort/order keys in JavaScript objects?
(9 answers)
Closed last year.
I could add "id" to each object in the array "data":
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
for(const key in data) {
data[key]['id'] = key;
}
console.log(data);
But "id" is added to the last in each object in the array "data":
[
{ name: "John", age: 24, id: "0" },
{ name: "Marry", age: 18, id: "1" },
{ name: "Tom", age: 15, id: "2" }
]
My desired result is this below adding "id" to the first in each object in the array "data":
[
{ id: "0", name: "John", age: 24 },
{ id: "1", name: 'Marry', age: 18 },
{ id: "2", name: 'Tom', age: 15 }
]
Are there any ways to do that?
Create the array "newData" with "id" and the array "data":
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: key,
...data[key]
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: "0", name: "John", age: 24 },
{ id: "1", name: 'Marry', age: 18 },
{ id: "2", name: 'Tom', age: 15 }
]
In addition, if you want "id" of Number type, use "Number()":
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: Number(key), // Here
...data[key]
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: 0, name: "John", age: 24 },
{ id: 1, name: 'Marry', age: 18 },
{ id: 2, name: 'Tom', age: 15 }
]

how to replace array of object with an object in javascript without repeating

let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2={ name: "jack", age: 30 }
case1:
i expect the result to be
[{ name: "ben", age: 10 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
where "ben" is existing so it replaces age to 10
case2:
i expect the result to be
[{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 },{ name: "jack", age: 30 }]
where "jack" is not there in the array so it adds to the array
how to write a function which does this functionality
Yours is a good case for Array.prototype.findIndex (MDN), which is like Array.prototype.find but returns the found index instead of the item.
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2 = { name: "jack", age: 30 }
const arrayUpsert = function (array, object) {
const objectIndex = array.findIndex(item => item.name == object.name)
if (objectIndex == -1) {
array.push(object)
} else {
array[objectIndex] = { ...array[objectIndex], ...object }
}
return array
}
console.log(arrayUpsert(a, case1))
console.log(arrayUpsert(a, case2))
/* [
{ name: 'ben', age: 10 },
{ name: 'jeffrey', age: 10 },
{ name: 'daniel', age: 20 }
]
[
{ name: 'ben', age: 10 },
{ name: 'jeffrey', age: 10 },
{ name: 'daniel', age: 20 },
{ name: 'jack', age: 30 }
] */
Can be done with a for loop as well.
function untitled(original, newObj) {
for (let index = 0; index < original.length; index++) {
if (original.name && newObj.name === a[index].name) {
original[index] = {...newObj};
console.log(original); return;
}
}
original.push(newObj); console.log(original);
}
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2 = { name: "jack", age: 30 }
untitled(a, case1);
untitled(a, case2);
I'm using ramda library in my solution:-
Check whether the key exist in any of the object in array by
idx = R.findIndex(R.propEq('name', 'ben'), a). If idx<0 then we can directly push the object else go to the next step.
We have the index(idx), we just have to do a[idx].age="--".

increment the duplicate value of object in any array of objects in java script

I have a 5 age fields where user can enter same value they are not validating
while sending to the API. I have to increment the duplicate ages in ech object.
for ex - if user gives ages like 10, 11, 10, 10, 20 i need it as 10,11,12,13,20 like this
Here is the variable having duplicate:
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt"
age: 13
},
{
name: "Nancy",
age: 13
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 23
},
{
name: "Nancy",
age: 22
}
];
where every duplicate values comes i have to increment by checking all the ages in each object i need out put like this --> here age 13 and 22 is duplicating i have to check all ages and i have to increment 2nd repeted age by +1 -->
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt"
age: 13
},
{
name: "Nancy",
age: 14
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 23
},
{
name: "Nancy",
age: 24
}
];
note my array will have only 5 objects
Try with below code. Hope this will be help u.
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt",
age: 13
},
{
name: "Nancy",
age: 13
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 23
},
{
name: "Nancy",
age: 22
}
];
var ind = [];
family.forEach(a => {
cur = a.age;
while (ind[cur] === 1) {
cur++;
}
ind[cur] = 1;
a.age = cur;
});
family.forEach(a => console.log(a.age));
Another update:
var order = family.map((person, index) => {
return { index, person };
}).sort((a, b) => {
if (a.person.age === b.person.age) {
return a.index - b.index;
}
return a.person.age > b.person.age ? 1 : -1;
});
var prevAge = 0;
order.forEach(item => {
if (item.person.age <= prevAge) {
item.person.age = ++prevAge;
}
prevAge = item.person.age;
family.filter(f => f.name === item.person.name)[0].age = item.person.age;
});
Please, try the different cases I put in the demo and check if the results are what you would expect.
Stackblitz: https://stackblitz.com/edit/typescript-far3zq

how to update an array element property with another array element property in underscore.js

First array
userData = [
{ name: abc, age: 24 },
{ name: ghi, age: 22 },
{ name: tyu, age: 20 }
];
Second array
userAge = [
{ age: 25 },
{ age: 26 },
{ age: 22 }
];
Both arrays have the same length.
How do I update the useData[0].age with userAge[0] using Underscore.js?
Since you need to do this over a list of dictionaries, you will need to iterate over the list using _.each.
Something like this will help,
_.each(userData, function(data, index) {
data.age = userAge[index].age;
});
While #martianwars is correct, it could be a little more generic, thus more useful, if it could apply any attribute.
Say we have an array of changes to apply, with each not being necessarily the same attribute or even multiple attributes per object:
var changes = [
{ age: 25 },
{ name: "Guy" },
{ name: "Pierre", age: 22 }
];
Changes could be applied with _.extendOwn
_.each(userData, function(data, index) {
_.extendOwn(data, changes[index]);
});
Proof of concept:
var userData = [{
name: "abc",
age: 24
}, {
name: "ghi",
age: 22
}, {
name: "tyu",
age: 20
}];
var changes = [{
age: 25
}, {
name: "Guy"
}, {
name: "Pierre",
age: 22
}];
_.each(userData, function(data, index) {
_.extendOwn(data, changes[index]);
});
console.log(userData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This will only work if the arrays are in sync. Meaning that if there are 4 objects in the userData array, and only 3 changes, they need to be at the right index and that could become a problem.
A solution to this is to have an identification property, often represented by an id attribute.
userData = [
{ id: '1', name: 'abc', age: 24 },
{ id: '2', name: 'ghi', age: 22 },
{ id: '3', name: 'tyu', age: 20 }
];
See Merge 2 objects based on 1 field using Underscore.js for details.

Categories