展开JS对象并转换数组 [英] Unflatten JS object and convert arrays
问题描述
我有一个用于平整对象的函数,如下所示:
I have a function used to flatten objects like so:
let object = {
a: 1,
b: [
{ c: 2 },
{ c: 3 }
]
};
flatten(object)
// returns {
'a': 1,
'b.0.c': 2,
'b.1.c': 3
}
我需要展开对象,还要将数组还原为原来的样子.我有以下代码:
I need to unflatten objects, but also revert arrays to how they were. I have the following code:
unflatten(obj) {
let final = {};
for (let prop in obj) {
this.assign(final, prop.split('.'), obj[prop]);
}
return final;
}
assign(final, path, value) {
let lastKeyIndex = path.length-1;
for (var i = 0; i < lastKeyIndex; ++ i) {
let key = path[i];
if (!(key in final)) {
final[key] = {};
}
final = final[key];
}
final[path[lastKeyIndex]] = value;
}
在大多数情况下都有效,但是它像这样对待数组:
which works for the most part, but it treats arrays like so:
{
a: 1,
b: { // Notice how b's value is now an object
"0": { c: 2 }, // Notice how these now have a key corresponding to their index
"1": { c: 3 }
}
}
我需要b
像以前一样是一个数组:
Whereas I need b
to be an array like before:
{
a: 1,
b: [
{ c: 2 },
{ c: 3 }
]
}
我不知道该从哪里去.它需要能够处理任意数量的数组,例如:
I'm at a loss for where to go from here. It needs to be able to deal with an arbitrary number of arrays like:
'a.b.0.c.0.d',
'a.b.0.c.1.d',
'a.b.1.c.0.d',
'a.b.1.c.1.d',
'a.b.1.c.2.d',
// etc
它必须是原始JS,但es2015很好.它假定任何一个数字键实际上都是数组的一部分.
It needs to be vanilla JS, but es2015 is fine. It it assumed that any key that's a number is actually part of an array.
如果有人有任何建议,我们将不胜感激!
If anyone has any advice, it's appreciated!
推荐答案
当发现key
不在final
中时,应检查路径中的下一个键是否仅为数字(使用常规表达式),如果是这样,则分配给数组而不是对象:
When you find that key
is not in final
, you should check to see if the next key in the path is only digits (using a regular expression) and, if so, assign to an array instead of an object:
if (!(key in final)) {
final[key] = /^\d+$/.test(path[i + 1]) ? [] : {};
}
let object = {
a: 1,
b: [{
c: 2
},
{
c: 3
}
]
};
let flattened = {
'a': 1,
'b.0.c': 2,
'b.1.c': 3
}
function unflatten(obj) {
let final = {};
for (let prop in obj) {
assign(final, prop.split('.'), obj[prop]);
}
return final;
}
function assign (final, path, value) {
let lastKeyIndex = path.length - 1;
for (var i = 0; i < lastKeyIndex; ++i) {
let key = path[i];
if (!(key in final)) {
final[key] = /^\d+$/.test(path[i + 1]) ? [] : {};
}
final = final[key];
}
final[path[lastKeyIndex]] = value;
}
console.log(unflatten(flattened))
.as-console-wrapper { min-height: 100vh; }
这篇关于展开JS对象并转换数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!