0

I get a json-style result from an $http GET in angularJS. It looks like this:

{
    "meta":{
    "limit":1000,
},
"objects":[
    {
        "custom_pk":"1",
        "linked_client":null,
        "resource_uri":"/api/v1/card_infos/1"
    },
    {
        "custom_pk":"2",
        "linked_client":null
    }, ...

I'd like to have an array which contains all custom_pk values to do something like:

$scope.validate_pk = function(val){
    if (val in myArray)
        // do some stuff

How do you create myArray?

2 Answers 2

2

You could extract the objects like this:

var json = ... the javascript object shown in your question
var custom_pks = [];
for (var i = 0; i < json.objects.length; i++) {
    custom_pks.push(json.objects[i].custom_pk);
}
// at this stage the custom_pks array will contain the list of all
// custom_pk properties from the objects property
Sign up to request clarification or add additional context in comments.

2 Comments

Thx it works! As I'm going to do these kind of operations a lot, is there a simpler/cleaner way to proceed? Am I supposed to write some loops when I want to parse json?
You could also move this common functionality in a reusable function that you would invoke. The name of the property could also be dynamic: custom_pks.push(json.objects[i]['custom_pk']); allowing you more flexibility if you want to externalize this functionality and work against any property.
1

I would prefer to use the .map() Array function:

var myArray = json.objects.map(function(item){
    return item.custom_pk;
});

Array.map() takes a function as an argument. This function is executed once for each value in the array and gets passed (item, index, list) as parameters. The result of the map function is a new array containing the results of the passed function.

Comments

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.