我在数组中有卖家和买家信息,我需要检查id是否与数组中的卖家或买家ID匹配,然后我需要从数组中删除该对象。
这是数组:
[
{
"transactionId": null,
"buyer": {
"userId": "eu-central-1",
"email": "pic@gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-2",
"email": "pic2@gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}
]
我有用户ID eu-central-2
。我希望 expected output
为
[
{
"transactionId": null,
"user": {
"userId": "eu-central-1",
"email": "pic@gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
}
}
]
我尝试了什么
let data = results.filter(result=> seller.userId || buyer.userId == userId);
问题是删除部分并重命名用户。
答案 0 :(得分:2)
var userId = 'eu-central-2';
var results = [
{
"transactionId": null,
"buyer": {
"userId": "eu-central-1",
"email": "pic@gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-2",
"email": "pic2@gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}
];
如果要删除整个对象,请使用以下对象:
var data = results.filter(function(a) {
if(a.buyer.userId == userId || a.seller.userId == userId) {
return false;
}
return true;
});
或者,如果您要删除特定买方或卖方,请使用以下网址:
var data = results.filter(function(a) {
if(a.buyer.userId == userId) {
delete a.buyer;
} else if(a.seller.userId == userId) {
delete a.seller;
}
if(a.buyer) {
a['user'] = a.buyer;
delete a.buyer;
} else if(a.seller) {
a['user'] = a.seller;
delete a.seller;
}
return true;
});
console.log(data);
答案 1 :(得分:1)
我建议使用以下代码:
results.map(result => ({
transactionId: result.transactionId,
user: [result.buyer, result.seller]
[1-[result.buyer, result.seller].findIndex(user => user.userId === userId)]
})).filter(result => result.user);
const results = [
{
"transactionId": null,
"buyer": {
"userId": "eu-central-1",
"email": "pic@gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-2",
"email": "pic2@gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}, {
"transactionId": null,
"buyer": {
"userId": "eu-central-3",
"email": "pic@gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-4",
"email": "pic2@gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}
];
const userId = "eu-central-2";
const data = results.map(result => ({
transactionId: result.transactionId,
user: [result.buyer, result.seller]
[1-[result.buyer, result.seller].findIndex(user => user.userId === userId)]
})).filter(result => result.user);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
您需要对您的陈述更具体一点,因为javascript可能无法达到预期效果。如果我理解正确,您需要以下内容:
seller.userId === userId
OR
buyer.userId === userId
如果这是您想要的,那么used语句将无法工作,因为JS会将其视为:
seller.userId === true
OR
buyer.userId === userId
您可能需要做的只是提及userId两次,并使用这样的括号:(seller.userId == userId) || (buyer.userId == userId)