Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific properties from Array objects in Node.js

For example I have this array, if I stringfy it it would be like this:

[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]

How can I do for remove from the 2 cars: the doors and price. And only leave in the array "car" and "id"? For example:

[{"car":"Toyota","ID":"1"},{"car":"Chevrolet","ID":"2"}]

Thank you!

like image 327
Matias Rodriguez Avatar asked Sep 17 '26 10:09

Matias Rodriguez


2 Answers

let arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]

let arr1 = arr.map(({car, ID}) => ({car, ID}));
let arr2 = arr.map(({Doors, price, ...remainingAttrs}) => remainingAttrs);

console.log('arr1:', arr1);
console.log('arr2:', arr2);

With ES6 syntax, you can deconstruct each object to create new one without writing a loop.

In your case, total number of fields remaining is same as the total number of deleted Following are the two approaches:

  • If less number of fields are to be preserved, then you can go with:

const arr1 = arr.map(({car, ID}) => ({car, ID}))

  • If less number of fields are to be removed, then you can go with:

const arr2 = arr.map(({Doors, price, ...remainingAttrs}) => remainingAttrs)

like image 195
Parth Mansata Avatar answered Sep 19 '26 00:09

Parth Mansata


You can use Array.prototype.map() to customise your result array, taking a callback function as parameter which returns a new customised object, having only car and ID properties, in each iteration.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

This is how should be your code:

var results = arr.map(function(item){
  return {car : item["car"], ID : item["ID"]}
});

Demo:

var arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];

var results = arr.map(function(item){
  return {car : item["car"], ID : item["ID"]}
});
console.log(JSON.stringify(results));
like image 37
cнŝdk Avatar answered Sep 18 '26 22:09

cнŝdk