Reputation: 115
I'll just ask on how to remove some elements in an object array using lodash.
var fruits = [
{ id: 1, name: 'Apple', price: 55, qty: 3, status: 'ripe' },
{ id: 2, name: 'Banana', price: 55, qty: 4, status: 'ripe' },
{ id: 3, name: 'Pineaple', price: 55, qty: 2, status: 'ripe' }
];
How will I remove the qty and status in all object array so it will look like this
[
{ id: 1, name: 'Apple', price: 55 },
{ id: 2, name: 'Banana', price: 55 },
{ id: 3, name: 'Pineaple', price: 55 }
]
Upvotes: 1
Views: 127
Reputation: 784
It is true that you don't need to use a library to effectively delete properties of an object though if you want to use lodash here is an example of how you would do that by using the .pick
method:
let pickedFruits = [];
for (let i in fruits) {
pickedFruits.push(_.pick(fruits[i], ["id", "name", "price"]));
}
where pickedFruits
will be the new array of objects each having an id
, name
and a price
property.
Upvotes: 0
Reputation: 4553
You can just iterate through the object using
forEach
and delete the unwanted fields with the plain olddelete
operator.
This method cleans your current object, Without the need for a new object to be defined.
fruits.forEach((val) => {delete val.qty; delete val.status})
Upvotes: 2
Reputation: 28455
You can do it without using a library too.
Use Array.map
var fruits = [{ id: 1, name: 'Apple', price: 55, qty: 3, status: 'ripe' },{ id: 2, name: 'Banana', price: 55, qty: 4, status: 'ripe' },{ id: 3, name: 'Pineaple', price: 55, qty: 2, status: 'ripe' }];
let result = fruits.map(({status,qty,...rest}) => rest);
console.log(result);
Upvotes: 2
Reputation: 26844
Without any library, you can use map
and destructure the object.
var fruits = [{"id":1,"name":"Apple","price":55,"qty":3,"status":"ripe"},{"id":2,"name":"Banana","price":55,"qty":4,"status":"ripe"},{"id":3,"name":"Pineaple","price":55,"qty":2,"status":"ripe"}]
var result = fruits.map(({qty,status,...r}) => r);
console.log(result);
Upvotes: 3