繁体   English   中英

如果 object 和数组值在 javascript 中匹配,如何获取 object 密钥

[英]how to get the object key if the object and array value matches in javascript

我想知道如何比较 javascript 中的 object 值和数组值

如果array valueobject value相同,那么如何返回

object key中的 object 键值


var result = obj.values(obj).includes(arr2) ? 
'status: active' : 'status: inactive'

var obj = {
  "active": 12,
  "inactive": 14
  "neutral": 16
}

var arr1=[12]
var arr2=[12, 14]
var arr3=[12, 16]

Expected Output

//for arr1
status: active
// for arr2
status: active
status: neutral
// for arr3
status: active
status: inactive

您应该检查数组是否包含 object 值,反之亦然:

const matches = (object, array) => {
  for (const [key, value] of Object.entries(object)) {
    if (array.includes(value))
      return [key, value];
  }
};

这应该有效。

您可以简单地遍历数组,然后尝试获取值与数组value匹配的Object.entries(obj)返回的[key, value]元组。 找到后,返回元组中的key ,即:

arr.map(v => Object.entries(obj).find(x => x[1] === v)[0]);

注意:如果您的数组可能包含 object 中存在的值,则上面的代码将引发错误,因为.find()将返回 undefined。 如果是这种情况,您需要捕获使用无效值的情况(防御性设计):

arr.map(v => {
  const foundTuple = Object.entries(obj).find(x => x[1] === v);
  return foundTuple ? foundTuple[0] : null;
});

请参阅下面的概念验证:

 const obj = { "active": 12, "inactive": 14, "neutral": 16 } const arr1 = [12]; const arr2 = [12, 14]; const arr3 = [12, 16]; const invalid_arr = [12, 999]; function getKeys(obj, arr) { return arr.map(v => { const foundTuple = Object.entries(obj).find(x => x[1] === v); return foundTuple? foundTuple[0]: null; }); } console.log(getKeys(obj, arr1)); console.log(getKeys(obj, arr2)); console.log(getKeys(obj, arr3)); console.log(getKeys(obj, invalid_arr));

另一种解决方案

 const obj = { "active": 12, "inactive": 14, "neutral": 16 } const arr1 = [12]; const arr2 = [12, 14]; const arr3 = [12, 16]; const getStatuses= (obj, arr) => arr.map(arrValue => { const [status] = Object.entries(obj).find(([objKey, objValue]) => objValue === arrValue)?? [null]; return { status }; }); console.log(getStatuses(obj, arr1)); console.log(getStatuses(obj, arr2)); console.log(getStatuses(obj, arr3));
 .as-console-wrapper{min-height: 100%;important: top: 0}

使用Object.keys()获取密钥,然后通过从原始 object 中获取值来过滤它们,并检查它是否包含在数组中:

 const getStatus = (obj, arr) => Object.keys(obj).filter(key => arr.includes(obj[key])) const obj = { "active": 12, "inactive": 14, "neutral": 16 } const arr1 = [12]; const arr2 = [12, 14]; const arr3 = [12, 16]; console.log(getStatus(obj, arr1)); console.log(getStatus(obj, arr2)); console.log(getStatus(obj, arr3));

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM