我有一个这样的对象:
data:
{
connection:
{
type: 0,
connected: false
},
acceleration:
{
x: 0,
y: 0,
z: 0,
watchId: 0,
hasError: false
}
},
将它转换为平面数组,如下所示:
"connected": false
"hasError": false
"type": 0
"watchId": 0
"x": 0
"y": 0
"z": 0
是一项简单的任务(重复是你的朋友!)。
但Javascript中是否有任何方法可以使用所谓的完整父母来获取它,例如:
"connection.connected": false
"acceleration.hasError": false
"connection.type": 0
"acceleration.watchId": 0
"acceleration.x": 0
"acceleration.y": 0
"acceleration.z": 0
或者我期待多少?
答案 0 :(得分:3)
总有一种方法,但请注意,这两个都是对象,也不是数组。 (Javascript中的关联数组只是对象)。
function objectFlatten( o , n ) {
var p = {}
, n = n? n : ''
, merge = function(a,b){ for( k in b) a[k] = b[k]; return a;}
;
for( i in o ) {
if( o.hasOwnProperty( i ) ) {
if( Object.prototype.toString.call( o[i] ) == '[object Object]' || Object.prototype.toString.call( o[i] ) == '[object Array]')
p = merge( p , objectFlatten( o[i] , n? n + '.' + i : i ) );
else
p[i] = o[i];
}
}
return p;
}
答案 1 :(得分:3)
另一种变体:
function flatten(o) {
var prefix = arguments[1] || "", out = arguments[2] || {}, name;
for (name in o) {
if (o.hasOwnProperty(name)) {
typeof o[name] === "object" ? flatten(o[name], prefix + name + '.', out) :
out[prefix + name] = o[name];
}
}
return out;
}
调用flatten(data);
答案 2 :(得分:2)
答案 3 :(得分:1)
我的五美分。
对于需要展平对象而非属性
的情况换句话说。
你有这样的事情:
var obj = {
one_a: {
second_a: {
aaa: 'aaa',
bbb: 'bbb'
},
second_b: {
qqq: 'qqq',
third_a: {
www: 'www',
eee: 'eee',
fourth_a: {
'rrr': 'rrr',
fifth: {
ttt: 'ttt'
}
},
fourth_b: {
yyy: 'yyy',
}
},
third_b: {
'uuu': 'uuu'
}
}
},
one_b: {
iii: 'iii'
}
}
并希望将嵌套对象设为平面,但不要想要平面属性:
{ 'one_a second_a ': { aaa: 'aaa', bbb: 'bbb' },
'one_a second_b ': { qqq: 'qqq' },
'one_a second_b third_a ': { www: 'www', eee: 'eee' },
'one_a second_b third_a fourth_a ': { rrr: 'rrr' },
'one_a second_b third_a fourth_a fifth ': { ttt: 'ttt' },
'one_a second_b third_a fourth_b ': { yyy: 'yyy' },
'one_a second_b third_b ': { uuu: 'uuu' },
'one_b ': { iii: 'iii' } }
代码:
function flatten (obj, includePrototype, into, prefix) {
into = into || {};
prefix = prefix || "";
for (var k in obj) {
if (includePrototype || obj.hasOwnProperty(k)) {
var prop = obj[k];
if (prop && typeof prop === "object" && !(prop instanceof Date || prop instanceof RegExp)) {
flatten(prop, includePrototype, into, prefix + k + " ");
}
else {
if (into[prefix] && typeof into[prefix] === 'object') {
into[prefix][k] = prop
} else {
into[prefix] = {}
into[prefix][k] = prop
}
}
}
}
return into;
}