基于值contact
为空的事实,我试图将一个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)
答案 0 :(得分:3)
您可以基于filter()
属性contact
。
如果列表非常大,可以使用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)
答案 1 :(得分:1)
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"
}
];
data.forEach(function(arrayItem, i) {
var x = arrayItem;
console.log(x);
});
答案 2 :(得分:1)
要获得预期的结果,请使用以下使用if条件的条件选项,如果contact为null则推送到变量
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){
empContactInfoAddress.push(data[d])
}else{
emergencyContactInfoAddress.push(data[d])
}
}
console.log('empContactInfoAddress', empContactInfoAddress)
console.log('emergencyContactInfoAddress', emergencyContactInfoAddress)
答案 3 :(得分:0)
您可以编写分区函数
function partition(array, predicate) {
const positives = array.filter(predicate);
const negatives = array.filter(value => !predicate(value));
return [positives, negatives];
}
const [
empContactInfoAddress,
emergencyContactInfoAddress
] = partition(data, d => !d.contact);