简体   繁体   English

如何检查数组是否包含值,这是对象的属性?

[英]How to check if array contains value, which is a property of an an object?

I have an object like this: 我有一个这样的对象:

    obj: {
          "abc": "xxxxx",
          "def": "yyyyy",
          "ghi": "zzzzz"
         }

and an array like this (only 1 value): 和这样的数组(只有1个值):

    array: ["def"]

result should be: 结果应该是:

    array: ["yyyyy"]

Im not sure what to try, thats why i didn't. 我不确定要尝试什么,这就是为什么我没有。 I hope you can help me with that 我希望你能帮助我

If the array really only has one entry, you can easily use that entry get the value of the property it names using brackets notation : 如果数组实际上只有一个条目,则可以使用括号轻松地使用该条目获取其命名的属性的值:

value = obj[array[0]];

To build a new array with just that value, you can use an array literal: 要仅使用该值构建新数组,可以使用数组文字:

[value]

So all together: 所以一起:

array = [obj[array[0]]];

Live example: 现场示例:

 const obj = { "abc": "xxxxx", "def": "yyyyy", "ghi": "zzzzz" }; let array = ["def"]; array = [obj[array[0]]]; console.log(array); 

You can use map method to do it... 您可以使用地图方法来做...

Code is: 代码是:

obj = {
   "abc": "xxxxx",
   "def": "yyyyy",
   "ghi": "zzzzz"
}

array = ["def", "abc"];

array = array.map(elem => {
    if(obj[elem]){
        return obj[elem];
    }
})

now array will be ["yyyyy", "xxxxx"] 现在数组将为[“ yyyyy”,“ xxxxx”]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查数组是否包含具有特定属性值的对象 - Check if array contains an object with the value of a specific property 检查哪个数组值也是对象属性 - Check which of an array value is also an object property 获取具有属性的数组中的对象,该属性是包含匹配值的数组 - Get an Object in an Array that has a property which is an Array that contains a matching value 在 JavaScript 中检查数组是否包含具有特定属性值的对象? - Check if an array contains an object with a certain property value in JavaScript? 使用javascript获取属性包含数组的对象作为值 - get the object which property contains an array as the value using javascript 如何检查包含另一个对象数组的对象数组是否具有属性 - How to check if array of objects that contains another array of object has property 如何找到对象的哪个属性包含特定值? - How to find which property of object contains specific value? 如何检查 JSON 对象数组是否包含数组中定义的值? - How to check if the JSON Object array contains the value defined in an arrary or not? 如何检查Javascript对象是否包含数组作为属性值? - How to check if a Javascript object contains an array as a value for an attribute? 如何检查 JSON 对象数组是否包含定义的值? - How to check if the JSON Object array contains the value defined or not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM