Có hai cách truy cập key lồng nhau trong Object.
Ví dụ object:
const obj = {
object: {
foo: {
bar: {
ya: 100
}
}
}
};Cách 1: obj['object']['foo']['bar']['ya']
Cách 2: obj.object.foo.bar.ya
Viết hàm chuyển chuỗi đường dẫn kiểu Cách 1 sang ký pháp dấu chấm Cách 2.
Ví dụ
Mã minh họa:
const obj = { "object[foo][bar][ya]": 100 };
const constructDotNotation = obj => {
const keys = Object.keys(obj)[0].split('[').map(el => el.replace(']', ''));
let res = {};
keys.reverse().forEach(key => {
if (Object.keys(res).length === 0){
res[key] = obj[Object.keys(obj)[0]];
}else{
const temp = {};
temp[key] = res;
res = temp;
};
});
return res;
};
console.log(JSON.stringify(constructDotNotation(obj), undefined, 4));Kết quả
Đầu ra:
{
"object": {
"foo": {
"bar": {
"ya": 100
}
}
}
}