0

this is my json object. i need to get only all the values of packageName and assign it to an array. can any body help me with that. i can not go for using indexes since this is dynamic object.
thanks in advance.

var data = [
    {
        "packageName":"string",
        "packageValue":"string"
    },
    {
        "packageName":"string",
        "packageValue":"string"
    }
]
0

3 Answers 3

1

Use javascript map function

var packageNames = data.map(function(obj){
   return obj.packageName;
})

var data=[  
   {  
      "packageName":"string1",
      "packageValue":"string"
   },
   {  
      "packageName":"string2",
      "packageValue":"string"
   }
] 

var packageNames = data.map(function(obj){
return obj.packageName;
})

console.log(packageNames)

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

Comments

0

You can use filter function and add to array only when this key exists.

var arr = [];

data.filter(getValue)

function getValue(data){
 if(data[packageName]){
   arr.push(data[packageName])
  }
}

Comments

0

You can add an if statement to check the key and then push it to an array.

for(var i = 0; i< data.length; i++){
    for (var property in data[i]) {
        if (data[i].hasOwnProperty(property)) {
            console.log(property);
            console.log(data[i][property]);
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.