3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
只需連接數(shù)組:
const obj1 = {
"countries": [{
"Country name": "China",
"Flag": "CN",
"Population": 1395380000,
"undefined": "#688144"
}
]
};
const obj2 = {
"countries": [{
"Country name": "India",
"Flag": "IN",
"Population": 1338677000,
"undefined": "#B78A31"
}
]
};
const result = {
countries: [...obj1.countries, ...obj2.countries]
};
console.log(result);

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用創(chuàng)建一個(gè)具有相同countries
屬性的新對(duì)象Array#concat
并將所有國(guó)家/地區(qū)數(shù)組合并為一個(gè):
const obj1 = {
"countries": [{
"Country name": "China",
"Flag": "CN",
"Population": 1395380000,
"undefined": "#688144"
}, /* ... */ ]
};
const obj2 = {
"countries": [{
"Country name": "India",
"Flag": "IN",
"Population": 1338677000,
"undefined": "#B78A31"
}, /* ... */ ]
};
const obj3 = {
"countries": [{
"Country name": "Sealand",
"Flag": "",
"Population": 27,
"undefined": "#0000FF"
}, /* ... */ ]
};
const combined = {
countries: [].concat(
obj1.countries,
obj2.countries,
obj3.countries
)
};
console.log(combined);
如果你有一個(gè)對(duì)象數(shù)組,你可以結(jié)合Array#map
擴(kuò)展語(yǔ)法來(lái)提取countries
數(shù)組并將它們組合成一個(gè):
const obj1 = { "countries": [{ "Country name": "China", "Flag": "CN", "Population": 1395380000, "undefined": "#688144" }, /* ... */ ]};
const obj2 = { "countries": [{ "Country name": "India", "Flag": "IN", "Population": 1338677000, "undefined": "#B78A31" }, /* ... */ ]};
const obj3 = { "countries": [{ "Country name": "Sealand", "Flag": "", "Population": 27, "undefined": "#0000FF" }, /* ... */ ]};
const objArr = [obj1, obj2, obj3];
const combined = {
combined: [].concat(
...objArr.map(x => x.countries)
)
};
console.log(combined)

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以push所有數(shù)組合二為一。
const obj1 = {
"countries": [
{
"Country name": "China",
"Flag": "CN",
"Population": 1395380000,
"undefined": "#688144"
}, ]}
const obj2 = {
"countries": [
{
"Country name": "India",
"Flag": "IN",
"Population": 1338677000,
"undefined": "#B78A31"
},]};
const res = [obj1, obj2, /*...*/]
.reduce((acc,{countries})=>(acc.countries.push(...countries),acc), {countries: []});
console.log(res);
添加回答
舉報(bào)