我有一个像这样的对象:
let myObj = [{
xyz: {
0: {
id: 1,
name: "Pimba"
//....
}
}
},
{
xyz: {
0: {
id: 2,
name: "Xablaw"
//....
}
}
}
];
我需要从内部数组获取所有属性,并将其向上放置一级。像这样:
let myObj = [{
xyz: {
id: 1,
name: "Pimba"
}
},
{
xyz: {
id: 2,
name: "Xablaw"
}
}
];
那有可能吗?试图与map()
一起使用而没有成功。
答案 0 :(得分:0)
let myObj = [{
xyz: {
0: {
id: 1,
name: "Pimba"
//....
}
}
},
{
xyz: {
0: {
id: 2,
name: "Xablaw"
//....
}
}
}
];
console.log(myObj.map(t => ({xyz: t.xyz[0]})));
myObj = myObj.map(t => ({xyz: t.xyz[0]}));
如果索引数量多于0,则可以使用以下方法合并对象:
myObj.map(t => ({xyz: Object.values(t.xyz).reduce((a,b) => Object.assign(a,b),{})}));
答案 1 :(得分:0)
尝试一下:
var myObj = [{
xyz: {
0: {//Properties Here - Inner Array}
a: 1,
b: 2
}
}
},
{
xyz: {
0: {//Properties Here - Inner Array}
a: 1,
b: 2
}
}
}];
var res = myObj.map(function (current, index, arr) {
var keys = Object.keys(current.xyz);
for (var k in keys) {
var inner = current.xyz[k];
delete current.xyz[k];
var innerKeys = Object.keys(inner);
for (var i = 0; i < innerKeys.length; i++) {
var innerK = innerKeys[i];
current.xyz[innerK] = inner[innerK];
}
}
return current;
});
console.log(res);
答案 2 :(得分:0)
基本上,您可以执行obj.map(item => shiftUp(item.xyz, "0"));
shiftUp是一个定义为以下功能的函数:
function shiftUp (obj, propName) {
if (obj.hasOwnProperty(propName)) {
for (let prop in obj[propName]) {
if (obj[propName].hasOwnProperty(prop)) {
obj[prop] = obj[propName][prop];
}
}
obj[propName] = undefined;
}
return obj;
}
JSFiddle在这里:https://jsfiddle.net/will_russell_coactive/0xjb2cv6/