我正在尝试使用递归转换以下对象:
const objToConvert = {
"article":[
{
"section@role":"Testing",
"section":[
{
"title@id":"title test",
"title": {
"content@id":"1",
"content":"some simple content"
}
}
]
}
]
};
到一个看起来像这样的对象:
const desiredObject = {
type: "article",
props: {
},
children: [
{
type: "section",
props: {
"section@role": "Testing"
},
children: {
type: "title",
props: {
"title@id":"title test",
"content@id":"1",
"content":"some simple content"
}
}
}
],
};
现在我对如何照顾 children 感到困惑。我尝试了不同的方法,但仍然无法使其正常工作。我有一个最初的解决方案,偶然使用数组而不是对象,但我需要它是一个对象。我真的迷失了..
jsfiddle:https://jsfiddle.net/7dmowrdj/3/
function nodeAttributes(obj) {
let attributeList = {};
for (var attrib in obj) {
const item = obj[attrib];
if (item && item.constructor === String && attrib.indexOf("@") !== -1) {
const attribVals = attrib.split("@");
const attribName = attribVals[1];
attributeList[attribName] = item;
}
if (attrib == "annotate")
attributeList[attrib] = item;
}
return attributeList;
}
function walkObject(obj, compStructure, objAttributes) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
const curAttributes = nodeAttributes(obj[property]);
const currentItem = {
type: property,
props: { ...objAttributes, ...curAttributes}
};
if (obj[property].constructor === Array) {
/* this work wont right */
//if (currentItem.children === undefined)
// currentItem.children = [];
//this.walkObject(obj[property], currentItem.children, curAttributes);
//compStructure = {...currentItem};
walkObject(obj[property], compStructure, curAttributes);
} else {
walkObject(obj[property], compStructure, curAttributes);
debugger;
if (!isNaN(parseInt(property)))
compStructure = currentItem;
debugger;
}
}
}
}
}
let compStructure = {};
walkObject(objToConvert, compStructure, {});
console.log(compStructure);
最佳答案
这是否符合您正在寻找的内容?它似乎可以处理给定的情况,但我可能会遗漏一些东西。
const objToConvert = {"article": [{"section": [{"title": {"content": "some simple content", "content@id": "1"}, "title@id": "title test"}], "section@role": "Testing"}]}
const convert = (obj) =>
Object.keys(obj).reduce((curr, key) => obj[key] instanceof Array
? Object.assign(curr, {type: key, props: curr.props, children: obj[key].map(convert)})
: obj[key] instanceof Object
? Object.assign(curr, {type: key, props: Object.assign(curr.props, obj[key])})
: Object.assign(curr, {props: Object.assign(curr.props, {[key]: obj[key]})})
, {props: {}})
console.log(convert(objToConvert))
可能需要进行一些清理工作。如果不出意外的话,我不喜欢该函数中的所有 obj[key] 实例。但我把清理工作留给读者作为练习。 :-)
关于javascript - 对象内的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590054/