如何将JavaScript对象平铺成像菊花链一样的形式? [英] How to flatten a JavaScript object into a daisy chain like form?
问题描述
我想平铺一个这样的对象...
I want to flatten an object like this...
var obj1 = {
firstName: 'John',
lastName: 'Green',
car: {
make: 'Honda',
model: 'Civic',
revisions: [
{ miles: 10150, code: 'REV01', changes: },
{ miles: 20021, code: 'REV02', changes: [
{ type: 'asthetic', desc: 'Left tire cap' },
{ type: 'mechanic', desc: 'Engine pressure regulator' }
] }
]
},
visits: [
{ date: '2015-01-01', dealer: 'DEAL-001' },
{ date: '2015-03-01', dealer: 'DEAL-002' }
]
};
...进入菊花链形式,如下所示:
... into a daisy chain form like the following:
{
"firstName": "John",
"lastName": "Green",
"car.make": "Honda",
"car.model": "Civic",
"car.revisions.0.miles": 10150,
"car.revisions.0.code": "REV01",
"car.revisions.0.changes": ,
"car.revisions.1.miles": 20021,
"car.revisions.1.code": "REV02",
"car.revisions.1.changes.0.type": "asthetic",
"car.revisions.1.changes.0.desc": "Left tire cap",
"car.revisions.1.changes.1.type": "mechanic",
"car.revisions.1.changes.1.desc": "Engine pressure regulator",
"visits.0.date": "2015-01-01",
"visits.0.dealer": "DEAL-001",
"visits.1.date": "2015-03-01",
"visits.1.dealer": "DEAL-002"
}
这是我的(失败)尝试:
Here's my (failed) attempt:
function flatten(obj) {
var flattenObject = {};
// iterate given object
for (let x in obj) {
if (typeof obj[x] == 'string') {
flattenObject[x] = obj[x];
}
if (typeof obj[x] == 'object') {
for (let y in obj[x]) {
flattenObject[x + '.' + y] = obj[x][y];
}
}
}
return flattenObject;
}
我很快开始不必要地重复代码,以菊花链链接内部对象和数组。这绝对是需要递归的东西。任何想法?
I quickly started repeating code unnecessarily in order to daisy chain inner objects and arrays. This is definitely something that needs recursion. Any ideas?
编辑:这个问题类似于其他 问题但不是重复。这个问题需要一个特定的符号和嵌套的对象和数组在同一时间。
This question is similar to other questions but not a duplicate. This question requires a specific notation and nested objects and arrays at the same time.
编辑:我也问过相反的,unflatten,在另一个问题。
I've also asked the opposite, unflatten, in another question.
推荐答案
您可以创建这样的递归函数,并且它重要的是将以前的键存储在一个字符串中。
You can create recursive function like this, and its important to store previous keys in one string.
var obj1 = {
firstName: 'John',
lastName: 'Green',
car: {
make: 'Honda',
model: 'Civic',
revisions: [
{ miles: 10150, code: 'REV01', changes: 0},
{ miles: 20021, code: 'REV02', changes: [
{ type: 'asthetic', desc: 'Left tire cap' },
{ type: 'mechanic', desc: 'Engine pressure regulator' }
] }
]
},
visits: [
{ date: '2015-01-01', dealer: 'DEAL-001' },
{ date: '2015-03-01', dealer: 'DEAL-002' }
]
};
function flatten(data, c) {
var result = {}
for(var i in data) {
if(typeof data[i] == 'object') Object.assign(result, flatten(data[i], c + '.' + i))
else result[(c + '.' + i).replace(/^\./, "")] = data[i]
}
return result
}
console.log(JSON.stringify(flatten(obj1, ''), 0, 4))
这篇关于如何将JavaScript对象平铺成像菊花链一样的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!