当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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 ?

网友答案:

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")
网友答案:

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"}
]
网友答案:

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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: