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"
}
]
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)
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])
}
}
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]);
}
}
}
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.