gpt4 book ai didi

javascript - UnderscoreJS - 如何使用迭代器之一展平对象?

转载 作者:行者123 更新时间:2023-12-02 17:29:00 25 4
gpt4 key购买 nike

我想做一个面包屑。我从后端获取数据,如下所示:

var object = {
"Department": {
"DeptCode": null,
"Description": "123",
"DeptName": {
"name": "xyz"
}
}}

并且使用下划线或 jquery 我想像这样修改对象:

var result = {
"Department.DeptCode": null,
"Department.Description": "123",
"Department.DeptName.name": "xyz"
}

我尝试使用 undscore,但没有得到任何结果。有人告诉我可能的方法来完成这件事吗?

我的尝试:

var lable = [];

_.each(object, function(key, obj){
var title = obj;
if(_.object(key)){
_.each(key, function(text,obj){
lable.push(title + '.' + obj + ':' + text);
})
}

});

console.log(lable);

Here is the fiddle

最佳答案

尝试创建一个递归函数,如下所示(基于您的 fiddle ):

var lable = {};

function flatten(object, title) {
_.each(object, function(key, obj){
var newTitle = obj;
if (key != null && typeof(key)=='object') {
flatten(key, (title) ? title + '.' + newTitle : newTitle);
} else {
lable[title + '.' + newTitle] = key;
}
});
};

flatten(object, '');

console.log(lable);

检查这个 fiddle :http://jsfiddle.net/ACZs8/2/

另一种选择,用闭包替换全局变量方法,以定义更可重用的扁平函数:

function flatten(mainObject) {
var lable = {};
flattenAux = function(object, title) {
_.each(object, function(key, obj){
var newTitle = obj;
if (key != null && typeof(key)=='object') {
flattenAux(key, (title) ? title + '.' + newTitle : newTitle);
} else {
lable[title + '.' + newTitle] = key;
}
});
};
flattenAux(mainObject, null);
return lable;
}

var testResult = flatten(object);

console.log(testResult);

fiddle 示例:http://jsfiddle.net/ACZs8/6/

关于javascript - UnderscoreJS - 如何使用迭代器之一展平对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23245676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com