1

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
  • 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 Commented Dec 8, 2017 at 20:11

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer.The "linq" I have mentioned is js implementation of it link
2

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

2 Comments

this is technically incorrect, as it'll return a list of objects that contain only the province_id, as opposed to returning a list of the full objects that match the specified id
Thanks for your answer but I want to select all the objects in the JSON where their province_id is equal to 'ABC' for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.