合并两个对象

时间:2013-10-12 05:56:09

标签: javascript

我正在寻找一种方法将两个对象组合成一个单独的函数或者减少我的行数的东西。

var fsInfo1 = {
    name: 'Joshua Velez',
    address:{
        street: '94-1411 Kulewa Loop ',
        city: 'Waipahu, ',
        state: 'HI'
    },
    gpa: [3.3,4.0,2.8]

}
var fsInfo2= {
    name: 'John Doe',
    address:{
        street: 'Some Street ',
        city: 'Wahiawa, ',
        state: 'HI'
    },
    gpa: [3.4,3.6,3.1]
}
     

console.log(“名称:”+ fsInfo1.name)

     

console.log(“地址:”+ fsInfo1.address ['street'] + fsInfo1.address ['city'] + fsInfo1.address ['state'])   console.log(“GPA:”+ fsInfo1.gpa [0],fsInfo1.gpa [1],fsInfo1.gpa [2])

     

console.log(“名称:”+ fsInfo2.name)

     

console.log(“地址:”+ fsInfo2.address ['street'] + fsInfo2.address ['city'] +> fsInfo2.address ['state'])   console.log(“GPA:”+ fsInfo2.gpa [0],fsInfo2.gpa [1],fsInfo2.gpa [2])

2 个答案:

答案 0 :(得分:1)

一种方法是:

var fsInfo1 = // same as before
var fsInfo2 = // same 
function logFsInfo(fsInfo) {
    console.log("Name "+fsInfo.name);
    console.log("Address "+fsInfo.address.street + fsInfo.address.city + fsInfo.address.state);
    console.log("GPA "+fsInfo.gpa.join(",")); //combine gpa values into a string separated by commas
}
logFsInfo(fsInfo1);
logFsInfo(fsInfo2);

但这实际上取决于你想在这里做什么。您是否正在打印出fsInfo数据?如果是这样,当然,只需执行此类操作即可打印出该数据。但是如果你想用fsInfo对象开始做其他事情,我建议创建一个类并将方法附加到它。但是,对于一个简单的用途来说,这将是完全矫枉过正的。

答案 1 :(得分:0)

var fsInfo1 = {
    name: 'Joshua Velez',
    address:{
        street: '94-1411 Kulewa Loop ',
        city: 'Waipahu, ',
        state: 'HI'
    },
    gpa: [3.3,4.0,2.8]

}
var fsInfo2= {
    name: 'John Doe',
    address:{
        street: 'Some Street ',
        city: 'Wahiawa, ',
        state: 'HI'
    },
    gpa: [3.4,3.6,3.1]
}
var obj = new Object();

obj[0] = fsInfo1;
obj[1] = fsInfo2;
var count = Object.keys(myArray).length;
for(i=0 ; i<count;i++)
{
      console.log("Name: " + obj[i].name)

console.log("Address: " + obj[i].address['street'] + obj[i].address['city'] + obj[i].address['state']) console.log("GPA: " + obj[i].gpa[0],obj[i].gpa[1],obj[i].gpa[2])
}