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.
- 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
2 Answers
Reset to default 5what 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);