Viết hàm nhận đối tượng JSON lồng nhau tùy ý độ sâu, trả về đối tượng phẳng với key dùng dấu chấm (dot notation).
Ví dụ: {one:1, two:{three:3}, four:{five:5, six:{seven:7}, eight:8}, nine:9} → {'one':1, 'two.three':3, 'four.five':5, 'four.six.seven':7, 'four.eight':8, 'nine':9}.
Ví dụ
const obj = {"one":1,"two":{"three":3},"four":{"five":5,"six":{"seven":7},"eight":8},"nine":9};
const flattenJSON = (obj = {}, res = {}, extraKey = '') => {
for (key in obj) {
if (typeof obj[key] !== 'object') res[extraKey + key] = obj[key];
else flattenJSON(obj[key], res, `${extraKey}${key}.`);
}
return res;
};
console.log(flattenJSON(obj));
Kết quả
{ one: 1, 'two.three': 3, 'four.five': 5, 'four.six.seven': 7, 'four.eight': 8, nine: 9 }