2

I have a JSON serialized collection:

[
    {
        "_id":"person1",
        "date":"7/20/2014 17:20:09",
        "listed_name":"Tom",
        "name":"Tom",
        "contact_info":"tom@gmail.com"
    },
    {
        "_id":"person2",
        "date":"7/20/2014 17:20:09",
        "listed_name":"Jane",
        "name":"Jane",
        "contact_info":"Person2@gmail.com"
    },
    {
        "_id":"person3",
        "date":"7/20/2014 17:20:09",
        "listed_name":"John",
        "name":"John",
        "contact_info":"Person3@gmail.com"
    }
]

And property name information coming from another page...

["_id", "date", "listed_name"]

The questions is...

Using JavaScript, how can I use the second array as a filter to return only the columns contained in the second array?

For instance: using this array ["_id"]... how can this array be used to only show the _id data for all JSON objects but keep out date, listed_name, name, etc...?

With the ["_id"] array as a filter, the expected console output should look like this:

person1
person2
person3
l3o
  • 123
  • 2
  • 6
  • As JSON is a string of platform independent, serialized data; and as you did not tag a language, I'll ask--into what language will you be unserializing this JSON data and attempting the manipulation about which you ask? – JAAulde May 28 '15 at 02:09
  • Have you tried anything thus far? Show us the code you've attempted, please. – JAAulde May 28 '15 at 02:13
  • ive tried quite a few different things. but give me a second to go back and look. – l3o May 28 '15 at 02:14
  • should i put the attempted code in here? or in the main question? – l3o May 28 '15 at 02:18
  • You should at least show an example of the expected output. Your explanation is helpful, but an example speaks volumes. – vol7ron May 28 '15 at 02:20

5 Answers5

3

Suppose you have your incoming JSON in a variable.

var parsedJSON = JSON.parse(inputJSON)
var filterArray = ["_id", "date"]

for (var i = 0; i < parsedJSON.length; ++i) {
    for (var filterItem in filterArray) {
        console.log(parsedJSON[i][filterArray[filterItem]])
    }
}
AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
Anurag Anand
  • 500
  • 1
  • 7
  • 13
2

If you define a little helper function called pick (or use underscore's _.pick) to pick out specified properties from an object, then in ES6 it's just

input . map(element = > pick(element, fields))

In English, with bold words associated with the code above:

Take the input and map each element in it to the result of picking from that element some specified fields.

or using array comprehensions

[ for (elt of input) pick(elt, fields) ]

or in ES5

input . map(function(elt) { return pick(elt, fields); })

How do you write pick? If you're writing in ES6 then

function pick(o, fields) {
    return Object.assign({}, ...(for (p of fields) {[p]: o[p]}));
}

See One-liner to take some properties from object in ES 6. That question also provides some non-ES6 alternatives, such as

function pick(o, fields) {
    return fields.reduce(function(result, field) {
        result[field] = o[field];
        return result;
    }, {});
}
Community
  • 1
  • 1
0

I would deserialize the array, then use .map on the result and within the map function loop over each of the items in the array of identifiers you want to keep, copying them to a new object, and returning that from the map. So in pseudocode:

var filters = [/* our array of identifiers to keep */];
var filtered = JSON.parse(unfiltered).map(function(currObj) {
  var temp = {};
  for identifier in filters:
    temp[identifier] = currObj[identifier];
  return temp;
});

This gives you your array of now filtered objects in the filtered variable.

Jack TC
  • 344
  • 1
  • 5
  • 17
0

Thanks for everyones help but I figured out a solution. Might not be the most efficient... don't know ... but it works. Here is the code in its entirety.

    $.getJSON( '/jsonData', function(data) {

            //Put JSON list data into variable.
            listData = data;
            //Get external query array.
            var parsedArray = JSON.parse([storedArray]); //console output:["_id", "date", "listed_name"]
            //Loop through parsedArray to get filters.
            for(var i=0;i<parsedArray.length;i++){
                //Put array items into variable.
                queryKeys = parsedArray[i];
                //Loop through all JSON data.
                for(var x=0;x<ListData.length;x++){
                    //filter output by queryKeys variable.
                    console.log(makerListData[x][queryKeys]);
                }
    });

console output:

person1
person2
person3
7/20/2014 17:20:09
7/20/2014 17:20:09
7/20/2014 17:20:09
Tom
Jane
John
l3o
  • 123
  • 2
  • 6
0

If you're willing to use a library, lodash makes this trivial:

function pick(collection, attributes) {
  return _(attributes)
    .map(function(attr) { return _.pluck(collection, attr); })
    .flatten()
    .value();
}

Examples:

pick(data, ['_id']);
// -> ["person1", "person2", "person3"]

pick(data, ['_id', 'date', 'listed_name']);
// -> ["person1", "person2", "person3", "7/20/2014 17:20:09", "7/20/2014 17:20:09", "7/20/2014 17:20:09", "Tom", "Jane", "John"]
Yony
  • 1,264
  • 1
  • 10
  • 19