[英]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.