newenthusiast newenthusiast - 2 months ago 9
Node.js Question

Filter an array of objects

I have data that looks like this:

[{address: '1300 BRYANT ST',
block: '3903',
cnn: '517000',
latitude: '37.7690871267671',
longitude: '-122.411527667132',
received: '2016-05-06',
x: '6009188.668',
y: '2108146.472' }, {B...}, {C...}]


I want to filter the data to look like this:

[{address: '1300 BRYANT ST',
latitude: '37.7690871267671',
longitude: '-122.411527667132'},
...]


How do I filter this data using JavaScript?

Answer

A simple way to do this is with the array .map() method:

var arr = [{address: '1300 BRYANT ST', block: '3903', cnn: '517000', latitude: '37.7690871267671', longitude: '-122.411527667132', received: '2016-05-06', x: '6009188.668', y: '2108146.472' }, {address: '12 ANOTHER ST', block: '3903', cnn: '517000', latitude: '12.7690871299999', longitude: '44.412300067132', received: '2016-05-06', x: '6009188.668', y: '2108146.472' }];

arr = arr.map(function(v) {
    return {
      address: v.address,
      latitude: v.latitude,
      longitude: v.longitude
    };
  });

console.log(arr);

In the code shown I've assigned the result back to the same variable, but you could assign it to a new variable if you need to keep a reference to the original full data.

By the way, regarding the original wording of your question, you don't have a "JSON object", because there is no such thing: you have either an object (in your specific case an array of objects), or JSON (as a string that needs to be parsed). What you show in your question is not valid JSON because JSON requires double-quotes not single-quotes, and property names must be quoted, but it is valid JS object literal syntax.

If your data actual is JSON, a string, then you would first parse it, then manipulate the resulting array. (And if you actually need it as JSON after that you'd re-stringify the result.)

var json = /* your string here */
var arr = JSON.parse(json);
// map here as above
var updateJson = JSON.stringify(arr);
Comments