2

I have a JSON serialized collection:

[
    {
        "_id":"person1",
        "date":"7/20/2014 17:20:09",
        "listed_name":"Tom",
        "name":"Tom",
        "contact_info":"[email protected]"
    },
    {
        "_id":"person2",
        "date":"7/20/2014 17:20:09",
        "listed_name":"Jane",
        "name":"Jane",
        "contact_info":"[email protected]"
    },
    {
        "_id":"person3",
        "date":"7/20/2014 17:20:09",
        "listed_name":"John",
        "name":"John",
        "contact_info":"[email protected]"
    }
]

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
5
  • 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? Commented May 28, 2015 at 2:09
  • Have you tried anything thus far? Show us the code you've attempted, please. Commented May 28, 2015 at 2:13
  • ive tried quite a few different things. but give me a second to go back and look. Commented May 28, 2015 at 2:14
  • should i put the attempted code in here? or in the main question? Commented May 28, 2015 at 2:18
  • You should at least show an example of the expected output. Your explanation is helpful, but an example speaks volumes. Commented May 28, 2015 at 2:20

5 Answers 5

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]])
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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;
    }, {});
}

Comments

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.

Comments

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

Comments

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

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.