gpt4 book ai didi

javascript 如何使对象内联

转载 作者:行者123 更新时间:2023-11-28 08:41:03 25 4
gpt4 key购买 nike

我有一些具有不同嵌套的对象。示例:
对象1

{
data: {somePage1.php:
{0:
{function:'getPrice',
item:'0568000085',
line: 6},
1:
{function:'getCurrency',
item:'066000089'
line: 9}
},
somePage2.php:...
}
}

对象2

data: {EUR:{currency:45.0417}USD:{currency:33.0346}}

等等。我需要的是函数,它将使任何对象内联

希望的结果是:

对象1

{row1:{key1:somePage1.php, key2:0, function:'getPrice', item:'0568000085', line:6}
row2:{key1:somePage1.php, key2:1, function:'getCurrency', item:'066000089', line:9}
row3:{key1:somePage2.php, key2:0, function: ... }
row4:...
}

对象2

{
row1:{key1:EUR, currency:45.0417}
row2:{key1:USD, currency:33.0346}
}

很明显我需要递归,但我无法弄清楚整个函数,如下所示:

    this.row = 0;
this.inline = function(d){
var that = this;
var data = d||that.data;//data have been append to this object onload
$.each(data, function(attr, value){
$.each(data[attr], function(att, val){
if(typeof(val) === 'object' || typeof(val) === 'array'){
that.inline(data[attr][att]);
}else{
$.each(data, function(){
that.row++;
});
console.log(value);
}
});
});
console.log('======> '+that.row);
},

最佳答案

function convert(d) {
var r = {}, j = 0;
for (var i in d) {
r['row'+(j++)] = flatten({key1:i}, d[i], 2);
}
return r;
}
function flatten(r, d, l) {
for (var i in d) {
var c = d[i];
if (c && typeof c == 'object') {
r['key'+l] = i;
flatten(r, c, l+1);
} else {
r[i] = c;
}
}
return r;
}

这使用递归并假设 json 是任意嵌套的,并将 key1、key2 等分配给那些值为非 null 对象的键。

编辑:修复为使第一个键使用 rowX (抱歉所有单字母变量名称)

关于javascript 如何使对象内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20490832/

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