我正在尝试展平包含在该对象内的对象的对象数组(但也可以包含更多对象)。结果格式应该只是对象数组。
现在是这样:
var array = [
{
nickname: "Johnny",
first_name: "John",
last_name: "Smith",
info: {
married: "yes",
kids_ages: []
}
},
{
{
nickname: "Ron",
first_name: "Ronald",
last_name: "Smith",
info: {
married: "no",
kids_ages: []
}
},
{
nickname: "Johnny",
first_name: "John",
last_name: "Smith",
info: {
married: "yes",
kids_ages: [17]
},
kids: {
first_name: "Harry",
last_name: "Smith
}
}
]
对于第一个条目应该是这样的:
{
nickname: "Johnny",
first_name: "John",
last_name: "Smith",
married: "yes"
kids_ages: []
},
答案 0 :(得分:1)
您可以从对象中取出info
并将该对象与其余对象分配给单个对象。
var array = [{ nickname: "Johnny", first_name: "John", last_name: "Smith", info: { married: "yes", kids_ages: [] } }, { nickname: "Ron", first_name: "Ronald", last_name: "Smith", info: { married: "no", kids_ages: [] } }, { nickname: "Johnny", first_name: "John", last_name: "Smith", info: { married: "yes", kids_ages: [17] }, kids: { first_name: "Harry", last_name: "Smith" } }],
flat = array.map(({ info, ...object }) => ({ ...object, ...info }));
console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }
通过保留外部对象的键作为前缀的另一种方法。
function getFlat(object, parent) {
return Object.assign({}, ...Object.entries(object).map(([k, v]) => {
if (v && typeof v === 'object' && !Array.isArray(v)) {
return getFlat(v, k);
}
return { [parent + (parent && '_') + k]: v };
}));
}
var array = [{ nickname: "Johnny", first_name: "John", last_name: "Smith", info: { married: "yes", kids_ages: [] } }, { nickname: "Ron", first_name: "Ronald", last_name: "Smith", info: { married: "no", kids_ages: [] } }, { nickname: "Johnny", first_name: "John", last_name: "Smith", info: { married: "yes", kids_ages: [17] }, kids: { first_name: "Harry", last_name: "Smith" } }],
flat = array.map(o => getFlat(o));
console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
根据我的评论:
尝试array.prototype.map
,然后在每个对象array.prototype.reduce
上。想想冲突。当孩子对象和父对象中有first_name
时,最后一个对象应做什么。您要保留两个,最后一个,第一个,一些随机的吗?
例如:
const flat = arr => arr.map(element =>
Object.entries(element).reduce((sum, [key, value]) => {
if (isObject(value)) {
return {...sum, ...value}
// or anything else to manage conflicts, depends on the way you want to handle it
}
return {...sum, [key]: value }
}, {}))