我有以下对象数组
let attendanceGroup = [
0: {-Lwk9gsgfsQHkUljyyr: "absent"}
1: {-Lwk98aagfaFTu0qNFJD: "absent"}
2: {-Lwk9BgBg05SygiRPKw8: "absent"}
3: {-LwkasdfgHHCHw9e-3vq: "absent"}
]
let membersPresent = [
0: {uid: -Lwk9BgBg05SygiRPKw8}
1: {uid: LwkasdfgHHCHw9e-3vq}
]
我需要找到例如-Lwk98aagfaFTu0qNFJD
的密钥,然后我需要更改“不存在”以显示。
我尝试只进行一次foreach,然后输入uid(即每个密钥中的键)。 在这里,我循环其他一些datamemberPresent,然后取出一个匹配的uid,我需要将其更改为present。
membersPresent.forEach(present => {
attendanceGroup[present.uid] = 'present';
})
这不起作用。有什么想法可以帮助我找到钥匙,然后将价值从现在改变为缺失?
答案 0 :(得分:1)
尝试使用array.map
直接搜索
const searchKey = '-Lwk98aagfaFTu0qNFJD';
const data = [
{'-Lwk9gsgfsQHkUljyyr': "absent"},
{'-Lwk98aagfaFTu0qNFJD': "absent"},
{'-Lwk9BgBg05SygiRPKw8': "absent"},
{'-LwkasdfgHHCHw9e-3vq': "absent"}
];
data.map(item => {
item[searchKey]? item[searchKey] = 'present': ''
})
console.log(data);
如果要比较另一个阵列的丢失,请选择此方法。
const membersPresent = [
{uid: '-Lwk9BgBg05SygiRPKw8'},
{uid: 'LwkasdfgHHCHw9e-3vq'}
]
const data = [
{'-Lwk9gsgfsQHkUljyyr': "absent"},
{'-Lwk98aagfaFTu0qNFJD': "absent"},
{'-Lwk9BgBg05SygiRPKw8': "absent"},
{'-LwkasdfgHHCHw9e-3vq': "absent"}
];
data.map(item => {
const dataItem = membersPresent.find(eachitem => eachitem.uid === Object.keys(item)[0])
if(dataItem) {
item[Object.keys(item)[0]] = 'present';
}
})
console.log(data);
希望这就是您想要的。
答案 1 :(得分:1)
let attendanceGroup = [
{"-Lwk9gsgfsQHkUljyyr": "absent"},
{"-Lwk98aagfaFTu0qNFJD": "absent"},
{"-Lwk9BgBg05SygiRPKw8": "absent"},
{"-LwkasdfgHHCHw9e-3vq": "absent"}
]
let membersPresent = [
{uid: "-Lwk98aagfaFTu0qNFJD"},
{uid: "-LwkasdfgHHCHw9e-3vq"}
]
membersPresent.forEach(present => {
let uid = present.uid; // User id of member who is present
// Search the user in attendanceGroup
for(let idx in attendanceGroup){ // idx is index of element i.e. 0,1,2,3,etc.
let member = attendanceGroup[idx]; // member from attendanceGroup. Ex {"-Lwk9gsgfsQHkUljyyr": "absent"}
if(uid in member) // Check if member id is same as given User id
attendanceGroup[idx][uid] = 'present'; // mark present
}
})
console.log(attendanceGroup)
输出
[ { '-Lwk9gsgfsQHkUljyyr': 'absent' },
{ '-Lwk98aagfaFTu0qNFJD': 'present' },
{ '-Lwk9BgBg05SygiRPKw8': 'absent' },
{ '-LwkasdfgHHCHw9e-3vq': 'present' } ]