JavaScript/VueJS:检查数组是否包含具有特定值的元素的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42023246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript/VueJS: Check if an Array contains an object with an element that has specific value
提问by SPQRInc
I would like to solve this problem:
我想解决这个问题:
I got an Object that contains a property named specs. This property contains an Arrayof Objectsthat all have 2 properties:
我有一个包含名为specs. 此属性包含Array的Objects所有的有2个属性:
- 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.
所以 - 现在我想检查一下,我的 Specs-Array 是否包含一个名为“Power”的项目。如果是这种情况,我想使用这个元素的值。
How can I solve this?
我该如何解决这个问题?
回答by Deep
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.
您可以根据 name 属性过滤数组并检查过滤器是否返回结果数组,如果是,则可以将其与索引一起使用以获取值。
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)
回答by Vinod Louis
consider the main object name is objTemp
考虑主要对象名称是 objTemp
you can do
你可以做
var arrR = objTemp.Specs.filter(function(ele){
return (ele.Name == "Power")
});
if(arrR.length)
//has prop
else
// no prop
回答by Saurabh
You can use somemethod on array, which will return true or false, depending on your condition, like following:
您可以在数组上使用一些方法,该方法将返回 true 或 false,具体取决于您的条件,如下所示:
var powerIndex
var doesPowerExist = yourObj.specs.some((spec, index) => {
var powerIndex = index
return spec.name == "Power"
})
You can use doesPowerExistvar to decided whether to use the value of this element.
您可以使用doesPowerExistvar 来决定是否使用该元素的值。
回答by Ankit Kumar Ojha
$.each(object.Specs,function(index,obj){
if(obj.Name === "Power")
var myVar = obj.Value
});

