gpt4 book ai didi

javascript - 如何检查对象键是否在另一个对象对象中

转载 作者:行者123 更新时间:2023-12-05 01:04:16 25 4
gpt4 key购买 nike

我有以下元素:

const allMembers = {
"-Lz8YxHiwp8QZW3TqAFn": {
"first": "foo",
"last": "bar",
"uid": "-Lz8YxHiwp8QZW3TqAFn"
},
"-Lz8YxHqQXWoaGOFRLrO": {
"first": "foo",
"last": "bar",
"uid": "-Lz8YxHqQXWoaGOFRLrO"
},
"-Lz8YxHsMItaaTVNyQRE": {
"first": "foo",
"last": "bar",
"uid": "-Lz8YxHsMItaaTVNyQRE"
},
"-Lz8YxHwuVBMWl0Go6C5": {
"first": "foo",
"last": "bar",
"uid": "-Lz8YxHwuVBMWl0Go6C5"
},
"-Lz8YxHy0S-QkDaE1PkX": {
"first": "foo",
"last": "bar",
"uid": "-Lz8YxHy0S-QkDaE1PkX"
},
}

const attendanceData = {
"-Lz8YxHiwp8QZW3TqAFn": true,
"-Lz8YxHqQXWoaGOFRLrO": true,
"-Lz8YxHsMItaaTVNyQRE": true,
"-Lz8YxHwuVBMWl0Go6C5": false,
"-Lz8YxHy0S-QkDaE1PkX": true,
"-Lz8YxIFA1XGVmaNfNr3": false,
"-Lz8YxIJVZnIIj7RgEzg": false,
}

我需要清理 allMembers 以仅在出勤数据中发现为 true 时才返回。这是我的尝试,但显然不起作用。另外,我这样做的方式必须在其他时间循环第一个。

const membersHere = Object.keys(allMembers).filter(memEl => Object.keys(attendanceData).find(attendEl => memEl == attendEl));

最佳答案

const 
allMembers = {'-Lz8YxHiwp8QZW3TqAFn': {first: 'foo',last: 'bar',uid: '-Lz8YxHiwp8QZW3TqAFn'},'-Lz8YxHqQXWoaGOFRLrO': {first: 'foo',last: 'bar',uid: '-Lz8YxHqQXWoaGOFRLrO'},'-Lz8YxHsMItaaTVNyQRE': {first: 'foo',last: 'bar',uid: '-Lz8YxHsMItaaTVNyQRE'},'-Lz8YxHwuVBMWl0Go6C5': {first: 'foo',last: 'bar',uid: '-Lz8YxHwuVBMWl0Go6C5'},'-Lz8YxHy0S-QkDaE1PkX': {first: 'foo',last: 'bar',uid: '-Lz8YxHy0S-QkDaE1PkX'}},
attendanceData = {'-Lz8YxHiwp8QZW3TqAFn': true,'-Lz8YxHqQXWoaGOFRLrO': true,'-Lz8YxHsMItaaTVNyQRE': true,'-Lz8YxHwuVBMWl0Go6C5': false,'-Lz8YxHy0S-QkDaE1PkX': true,'-Lz8YxIFA1XGVmaNfNr3': false,'-Lz8YxIJVZnIIj7RgEzg': false},
filteredMembers = Object.fromEntries(
Object.entries(allMembers).filter(([k]) => attendanceData[k])
);

console.log(filteredMembers);

您也可以使用 Array.prototype.reduce

const 
allMembers = {'-Lz8YxHiwp8QZW3TqAFn': {first: 'foo',last: 'bar',uid: '-Lz8YxHiwp8QZW3TqAFn'},'-Lz8YxHqQXWoaGOFRLrO': {first: 'foo',last: 'bar',uid: '-Lz8YxHqQXWoaGOFRLrO'},'-Lz8YxHsMItaaTVNyQRE': {first: 'foo',last: 'bar',uid: '-Lz8YxHsMItaaTVNyQRE'},'-Lz8YxHwuVBMWl0Go6C5': {first: 'foo',last: 'bar',uid: '-Lz8YxHwuVBMWl0Go6C5'},'-Lz8YxHy0S-QkDaE1PkX': {first: 'foo',last: 'bar',uid: '-Lz8YxHy0S-QkDaE1PkX'}},
attendanceData = {'-Lz8YxHiwp8QZW3TqAFn': true,'-Lz8YxHqQXWoaGOFRLrO': true,'-Lz8YxHsMItaaTVNyQRE': true,'-Lz8YxHwuVBMWl0Go6C5': false,'-Lz8YxHy0S-QkDaE1PkX': true,'-Lz8YxIFA1XGVmaNfNr3': false,'-Lz8YxIJVZnIIj7RgEzg': false},
filteredMembers = Object.entries(allMembers).reduce(
(r, [k, v]) => (attendanceData[k] && (r[k] = v), r),
{}
);

console.log(filteredMembers);

其他相关文件:

关于javascript - 如何检查对象键是否在另一个对象对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72397119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com