Reputation: 188
I would like to solve this problem:
I got an Object that contains a property named specs
. This property contains an Array
of Objects
that all have 2 properties:
So my object is like this:
Object
-Title
-Date
-Specs [Array]
-- [0] Name: "Power"
-- [0] Value: 5
-- [1] Name: "Weight"
-- [1] Value: 100
So - now I would like to check, if my Specs-Array contains an item that has the name "Power". If this is the case, I would like to use the value of this element.
How can I solve this?
Upvotes: 12
Views: 67639
Reputation: 9794
You can filter the array based on the name attribute and check if the filter returns a result array , if yes then you can use it with index to get the value.
var data = {specs:[{Name:"Power",Value:"1"},{
Name:"Weight",Value:"2"},{Name:"Height",Value:"3"}]}
var valObj = data.specs.filter(function(elem){
if(elem.Name == "Power") return elem.Value;
});
if(valObj.length > 0)
console.log(valObj[0].Value)
Upvotes: 25
Reputation: 4876
consider the main object name is objTemp
you can do
var arrR = objTemp.Specs.filter(function(ele){
return (ele.Name == "Power")
});
if(arrR.length)
//has prop
else
// no prop
Upvotes: 5
Reputation: 73589
You can use some method on array, which will return true or false, depending on your condition, like following:
var powerIndex
var doesPowerExist = yourObj.specs.some((spec, index) => {
var powerIndex = index
return spec.name == "Power"
})
You can use doesPowerExist
var to decided whether to use the value of this element.
Upvotes: 0
Reputation: 97
$.each(object.Specs,function(index,obj){
if(obj.Name === "Power")
var myVar = obj.Value
});
Upvotes: 0