简体   繁体   中英

How to search in nested JSON data in vuejs?

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM