BOBIN JOSEPH
BOBIN JOSEPH

Reputation: 1022

Selecting item from JSON object and return as JSON object like C# LINQ

I have a JSON Object with large amount of data. I want to pass an JSON object to the web method that only need to contain the list of one value. Using $.grep we can filter the data like LINQ. But we cannot select the item. (*as per my knowledge). Is there any alternative. I dont want to use any JS Plugins apart from Jquery (like Underscore js) !

Let me explain with example data. If my Json object is like this.

data ={"employees":[
    {"firstName":"John", "lastName":"Doe" , "Age":"12"},
    {"firstName":"Anna", "lastName":"Smith", "Age":"13"},
    {"firstName":"Peter", "lastName":"Jones", "Age":"42"}
]};

I want the result set like ,

data ={"employees":[
    { "Age":"12"},
    { "Age":"13"},
    { "Age":"42"}
]};

by without using, for or foreach loop ! Do any one know ?

Upvotes: 2

Views: 2047

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386756

You could use linq.js

var data = { employees: [{ firstName: "John", lastName: "Doe", Age: "12" }, { firstName: "Anna", lastName: "Smith", Age: "13" }, { firstName: "Peter", lastName: "Jones", Age: "42" }] },
    result = Enumerable.From(data.employees).Select('{Age:$.Age}').ToArray();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

Upvotes: 3

griffon vulture
griffon vulture

Reputation: 6774

You should use map:

var data ={"employees":[
    {"firstName":"John", "lastName":"Doe" , "Age":"12"},
    {"firstName":"Anna", "lastName":"Smith", "Age":"13"},
    {"firstName":"Peter", "lastName":"Jones", "Age":"42"}
]};

function select(data, key, item){
  var selectedData = {}
  selectedData[key] = data[key].map(function(d){return d[item]}) 
  return selectedData;
}

select(data, "employees","Age")

Upvotes: 2

Alongkorn
Alongkorn

Reputation: 4217

if you change your data to an array instead of object. You can utilize Array feature, like this

const data =[
    {"firstName":"John", "lastName":"Doe" , "Age":"12"},
    {"firstName":"Anna", "lastName":"Smith", "Age":"13"},
    {"firstName":"Peter", "lastName":"Jones", "Age":"42"}
];

const data2 = data.map(item => {
  return {Age: item.Age}
})

data2 will look like this

data2 =[
    { "Age":"12"},
    { "Age":"13"},
    { "Age":"42"}
]

Upvotes: 1

Related Questions