1

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 }
]

4 Answers 4

3

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

2

You can just iterate through the object using forEach and delete the unwanted fields with the plain old delete 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})

3 Comments

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
@RoshanaPitigala, I have added the explanation. I didn't do it earlier because the operators I am using is basic and self explanatory.
@NarendraJadhav , I have added the explanation. I didn't do it earlier because the operators I am using is basic and self explanatory.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.