Filter an array of objects

Question!

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?



Answers

Assuming you have parsed your JSON to a JavaScript object called jsonData, you can just iterate the array and add like so:

var jsonData = ...;

var filteredData = [];

for (var i = 0; i < jsonData.length; i++) {
    filteredData.push({
        address: jsonData[i].address,
        latitude: jsonData[i].latitude,
        longitude: jsonData[i].longitude,
    });
}


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);
By : nnnnnn


Using plain JavaScript:

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

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

Here's a CodePen.

By : halim


This video can help you solving your question :)
By: admin