12

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:

  • name
  • value

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?

4 Answers 4

25

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)

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

Comments

5

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

2 Comments

Alright - and how could I access the ele.value if arrR is true? I would have to get the index of the array`s element in this case, right?
@SPQRInc arrR is an array of objects which has Name: "Power" so you can iterate over arrR and get value as arrR[0].Value and so on
0
$.each(object.Specs,function(index,obj){
if(obj.Name === "Power")
var myVar = obj.Value
});

3 Comments

if you use 'some' instead 'each', the loop will stop once you find a valid obj.
Thanks, wasn't aware of it until now. Very helpful
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
0

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.

2 Comments

Hello, thanks a lot for your answer. Now doesPowerExist would be true or false, right? How could I access the value where spec.name = "Power"?
@SPQRInc I have modified the code, powerIndex will be index of corresponding object, use this if doesPowerExist is true.

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.