admin管理员组

文章数量:1335594

I have nested JSON data like:

[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]

I want to filter the JSON by province_id and put it in another variable. Is there any solutions in VueJS such as Vue.filter(); ? I know we have "linq" which does the job but I do not want to use it.

I have nested JSON data like:

[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]

I want to filter the JSON by province_id and put it in another variable. Is there any solutions in VueJS such as Vue.filter(); ? I know we have "linq" which does the job but I do not want to use it.

Share Improve this question edited Dec 10, 2017 at 11:17 Amir Ghaffari eamirgh asked Dec 8, 2017 at 19:40 Amir Ghaffari eamirghAmir Ghaffari eamirgh 3141 gold badge4 silver badges16 bronze badges 1
  • 1 Can't you just set that to a variable, then loop over it looking at the providence_id property? var yourQuestionCode = [{"province_id":1}]; yourQuestionCode[0].province_id – DeadlyChambers Commented Dec 8, 2017 at 20:11
Add a ment  | 

2 Answers 2

Reset to default 5

what you're looking for is the javascript Array's filter() function. You should definitely spend some time getting familiar with filter, along with others like map and reduce. It'll make slicing and dicing your data much easier.

var serializedData = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var data = JSON.parse(serializedData);

var provinceAbc = data.filter(d => d.province_id === 'ABC');

That line will get you all objects where its province_id is "ABC"

Also, since you mentioned "linq" in your post, filter() is like IEnumerable.Where(), and map() is like IEnumerable.Select() in .NET Linq terms

I think this will work for you:

var nestedJson = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var array = JSON.parse(nestedJson);

array = array.map(e => e["province_id"]);

console.log(array);

本文标签: javascriptHow to search in nested JSON data in vuejsStack Overflow