[英]how to find certain key by its value into mixed objects array?
const items = [ { 'first': [205, 208, 222] }, { 'second': 205 } ]
I need to find keys by all coincidence into its value/values我需要通过所有巧合找到它的值/值的键
example:例子:
find key by id=205
, output: 'first', 'second'
通过
id=205
查找密钥,output: 'first', 'second'
find key by id=208
, output: 'first'
通过
id=208
查找密钥,output: 'first'
You can try getting the arrays of keys and values, then filter
the keys and check if the corresponding index in values
contain the variable id
.您可以尝试获取 arrays 的键和值,然后
filter
键并检查values
中对应的索引是否包含变量id
。
const items = [ { 'first': [205, 208, 222] }, { 'second': 205 } ] const id = 205; let keys = items.map(item => Object.keys(item)[0]); let values = items.map(item => Object.values(item)[0]); let output = keys.filter((_, index) => (values[index] == id || (typeof(values[index]) == 'object' && values[index].includes(id)))); console.log(output)
You can click on 'Run code snippet' and see the output as mentioned in the question您可以单击“运行代码片段”并查看问题中提到的 output
const items = [{ first: [205, 208, 222], }, { second: 205, }, ]; const toFind = 205; const fin = items.reduce((finalOutput, item) => { let key = Object.keys(item)[0]; if (Array.isArray(item[key])) { if (item[key].includes(toFind)) finalOutput.push(key); } else if (item[key] === toFind) { finalOutput.push(key); } return finalOutput; }, []); console.log(fin);
You can do something like this你可以这样做
const items = [ { 'first': [205, 208, 222] }, { 'second': 205 } ] const findKey = (data, value) => data.reduce((res, item) => { let [[key, v]] = Object.entries(item) v = Array.isArray(v)?v: [v] if(v.includes(value)){ return [...res, key] } return res }, []) console.log(findKey(items, 205)) console.log(findKey(items, 208))
Format your items
data properly, then:正确格式化您的
items
数据,然后:
const items = [ { 'first': [205, 208, 201] }, { 'second': [205] } ]
const findKeys = n => items.reduce((acc, obj) =>
Object.values(obj).some(arr => arr.includes(n)) ?
acc.concat(Object.keys(obj)) :
acc,
[])
const res = findKeys(208)
// Output: ['first']
console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.