如果我有来自原始文件的JSON数据。
[{"food": {"spicy": "spicy","sweet": "sweet"},
"water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}, {"food": {"spicy": "spicy","sweet": "sweet"},
"water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}]
我如何转换成这样的一维列表?
[{
"food-spicy": "spicy",
"food-sweet ": "sweet",
"water-sweet ": "sweet",
"water-sour-cold ": "ice lemon",
"water-sour-hot ": "lemon tea"
}, {
"food-spicy": "spicy",
"food-sweet ": "sweet",
"water-sweet ": "sweet",
"water-sour-cold ": "ice lemon",
"water-sour-hot ": "lemon tea"
}]
请帮忙。
最佳答案
您可以编写一个函数来递归地展平对象。然后使用该函数map
数组:
function flatten(oldObj) {
return Object.keys(oldObj).reduce(function(newObj, oldKey) { // for each key "oldKey" in oldObj
var value = oldObj[oldKey]; // get the value of the current oldKey from oldObj
if(value && typeof(value) === "object") { // if the value is also an object (add "&& !Array.isArray(value)" to exclude arrays)
value = flatten(value); // then flatten it first
Object.keys(value).forEach(function(key) { // and for each key in the new flattened value object
newObj[oldKey + "-" + key] = value[key]; // add a key-value to newObj where key is "oldKey-key" and the value is value[key]
});
} else {
newObj[oldKey] = value; // otherwise (if the value is not an object), just copy the key-value to newObj as it is
}
return newObj;
}, {});
}
然后像这样使用它:
var newArray = oldArray.map(flatten);
例:
function flatten(oldObj) {
return Object.keys(oldObj).reduce(function(newObj, oldKey) {
var value = oldObj[oldKey];
if(value && typeof(value) === "object") {
value = flatten(value);
Object.keys(value).forEach(function(key) {
newObj[oldKey + "-" + key] = value[key];
});
} else {
newObj[oldKey] = value;
}
return newObj;
}, {});
}
var oldArray = [{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}},{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}}];
var newArray = oldArray.map(flatten);
console.log(newArray);
关于javascript - 如何将多维列表转换为一维列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49932454/