gpt4 book ai didi

javascript - 将一个 JavaScript 对象分成两个单独的变量

转载 作者:行者123 更新时间:2023-11-29 16:36:09 24 4
gpt4 key购买 nike

如果值 contact 为 null,我试图根据事实将 JavaScript 对象分成两个单独的数组。我无法将值存储到单独的对象中,而且我不确定如何将它们存储在相应的对象中。我做了一个fiddle帮助您使用此代码。

var data = [{
address: "234 BLUE WAY",
addressType: "Mailing",
city: "DONKY KONG CITY",
contact: null,
country: "US",
email: "JANEER@GMAIL.COM",
zipCode: "44222"
},
{
address: "123 GETYO WAY",
addressType: "Mailing",
city: "NARNIA",
contact: "JAMES DO",
country: "US",
email: "JAMES@MYEMAIL.COM",
zipCode: "13123"
}

];

var empContactInfoAddress;
var emergencyContactInfoAddress;

for (let d in data) {
if (data[d].contact == null) {

Object.keys(data[d]).forEach((key) => {
this.empContactInfoAddress[d][key] = data[d][key];
});
} else {
Object.keys(data[d]).forEach((key) => {
this.emergencyContactInfoAddress[d][key] = data[d][key];
});

}
}
console.log('empContactInfoAddress', this.empContactInfoAddress)
console.log('emergencyContactInfoAddress', this.emergencyContactInfoAddress)

最佳答案

您可以根据contact 属性filter()

如果你有非常大的列表,你可以使用像 reduce 这样的东西,它可以让你通过一个循环遍历数据来做到这一点。但是 filter() 非常容易阅读,对我来说这平衡了额外的工作,除非有瓶颈。

var data = [{address: "234 BLUE WAY",addressType: "Mailing",city: "DONKY KONG CITY",contact: null,country: "US",email: "JANEER@GMAIL.COM",zipCode: "44222"},{address: "123 GETYO WAY",addressType: "Mailing",city: "NARNIA",contact: "JAMES DO",country: "US",email: "JAMES@MYEMAIL.COM",zipCode: "13123"}];

let NoContact = data.filter(d => d.contact == undefined)
let Contact = data.filter(d => d.contact)

console.log("no contact: ", NoContact)
console.log("contact: ", Contact)

关于javascript - 将一个 JavaScript 对象分成两个单独的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51295275/

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