[英]Get matching values of two objects
I have an object inboundTransfer
which contains an unknown number of keys.我有一个包含未知数量的密钥的 object
inboundTransfer
。 I would like to get all values from the itemNumbersList
properties which match the values on an array Object.keys(selectedItems)
.我想从
itemNumbersList
属性中获取与数组Object.keys(selectedItems)
上的值匹配的所有值。 The data that I receive looks a little something like this:我收到的数据看起来有点像这样:
const selectedItems = {
'nameX': {
propert1: 'value1',
property2: 'value2,
...
}
},
'nameY': {
...
},
'nameT': {
...
}
const inboundTransfers = {
0: {
property1: 'value1',
itemNumbersList: ['nameX', 'nameY', 'nameZ'],
},
1: {
property2: 'value2',
itemNumbersList: ['nameK', 'nameJ', 'nameT']
},
...
}
const isOnTransferlist = Object.keys(inboundTransfers)
.map((transfer) => Object.values(inboundTransfers[transfer].itemNumbersList)
.some((item) => Object.keys(selectedItems)
.indexOf(item) >= 0));
Obviously, I currently only check if the value is on both lists or not.显然,我目前只检查该值是否在两个列表中。 Ideally, I would like to get the value itself.
理想情况下,我想获得价值本身。 How could I achieve that?
我怎么能做到这一点? I tried using
.filter
instead of map
but with no success.我尝试使用
.filter
代替map
但没有成功。 Any help is much appreciated!任何帮助深表感谢!
I implemented this function and I test it, it works well.我实现了这个 function 并对其进行了测试,它运行良好。
function match() {
const selectedItems = {
a: "a1",
b: "b1",
};
const inboundTransfers = {
0: {
items: ["a", "b"],
},
1: {
items: ["c", "b"],
},
};
const capturedValues = []; // founded items store
[...Object.keys(selectedItems)].forEach((arrKey) => {
for (let [key, items] of Object.entries(inboundTransfers)) {
Object.values(items).forEach((item) => {
item.forEach((i) => {
if (i === arrKey) {
capturedValues.push(i);
}
});
});
}
});
// Remove redundant values
console.log([...new Set(capturedValues)]);
}
I found a way that works, but it's not very elegant, I guess:我找到了一种可行的方法,但我猜它不是很优雅:
const list = [];
Object.keys(inboundTransfers)
.forEach((transfer) => {
Object.values(inboundTransfers[transfer].itemNumbersList)
.forEach((item) => {
if (Object.keys(selectedItems).includes(item)) {
list.push(item);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.