const obj = {
uid: "893212",
a: {name: "Down here!", uid: "1231"},
b: {
c: {uid: "5965"},
name: "bud name",
},
d: {name: "doodle name"},
e: {name: "alexa name"},
f: ["kk", "jj"],
g: [
{
h: {uid: "47895"},
i: {uid: "4785"}
},
{
j: {uid: "4895"}
}
]
};
在上述物件中,如果“uid”存在,則其值應作為值應用于其父物件。結果應該如下
var result = {
uid: "893212",
a: "1231",
b: {c: "5965", name: "bud name"},
d: {name: "doodle name"},
e: {name: "alexa name"},
f: ["kk", "jj"],
g: [
{h: "47895", i: "4795"},
{j: "4895"}
]
}
我嘗試使用遞回函式來操作物件。
const mapObj = (obj = {}) => {
if (isObject(obj)) {
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i = 1) {
const [objK, objV] = entries[i];
if (isObject(objV) && 'uid' in objV) {
obj[objK] = objV['uid'];
} else if(isObject(objV)){
findNestedObject(objV);
} else if(isArray(objV)) {
objV.forEach(val => {
findNestedObject(val);
})
}
}
}
};
有什么簡單的方法可以做到這一點并轉換物件陣列
uj5u.com熱心網友回復:
嘗試這個:
const obj = {
uid: "893212",
a: {
name: "Down here!",
uid: "1231",
},
b: {
c: {
uid: "5965",
},
name: "bud name",
},
d: {
name: "doodle name"
},
e: {
name: "alexa name"
},
f: ["kk", "jj"],
};
const process = (anObject) => {
const toReturn = {};
Object.keys(anObject).forEach((key, index) => {
const currentProperty = anObject[key];
if(Array.isArray(currentProperty)) {
toReturn[key] = currentProperty;
}
else if(typeof(currentProperty) === 'object') {
const uid = currentProperty?.uid;
if(uid) {
toReturn[key] = uid;
}
else {
toReturn[key] = process(currentProperty);
}
} else {
toReturn[key] = currentProperty;
}
});
return toReturn;
}
const target = process(obj);
console.log(JSON.stringify(target, null, 2));
uj5u.com熱心網友回復:
在對子級呼叫遞回時將指標傳遞給父級的遞回。
const obj = {uid:"893212",a:{name:"Down here!",uid:"1231"},b:{c:{uid:"5965"},name:"bud name"},d:{name:"doodle name"},e:{name:"alexa name"},f:["kk","jj"],g:[{h:{uid:"47895"},i:{uid:"4785"}},{j:{uid:"4895"}}]};
function do_obj(obj, parent, parent_key) {
Object.keys(obj).forEach(function(key) {
var item = obj[key];
if (key === 'uid' && parent) {
parent[parent_key] = item;
}
if (typeof item === 'object' && item !== null) {
do_obj(item, obj, key);
}
})
}
do_obj(obj)
console.log(obj)
.as-console-wrapper {
max-height: 100% !important
}
uj5u.com熱心網友回復:
試試看:
const obj = { uid: "893212", a: {name: "Down here!", uid: "1231"}, b: { c: {uid: "5965"}, name: "bud name", }, d: {name: "doodle name"}, e: {name: "alexa name"}, f: ["kk", "jj"], g: [ { h: {uid: "47895"}, i: {uid: "4785"} }, { j: {uid: "4895"} } ] };
const refactor = (ins, depth) => {
if (Array.isArray(ins)) {
return ins.map(it => refactor(it, depth 1));
}
if (typeof ins === "object" && ins !== null) {
if (ins["uid"] && depth !== 0) return ins.uid;
return Object.entries(ins).reduce((a, [k, v]) => ({
...a,
[k]: refactor(v, depth 1)
}), {});
}
return ins;
}
console.log(refactor(obj, 0));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537308.html
標籤:javascript目的ecmascript-6ecmascript-5
上一篇:誰能幫我理解下面代碼的輸出
