提问人:Shankar Kumar 提问时间:4/26/2023 最后编辑:Shankar Kumar 更新时间:10/18/2023 访问量:76
如何将具有数组索引的对象解析为具有键值对的对象数组
How to parse an objects with array index to object array with key value pairs
问:
将此对象 Students 对象转换为一个 Students 数组
{"SubmitBy":"SK", "Students[0].name":"Jhon", "Students[0].age":"15", "Students[1].name":"Sam", "Students[1].age":"16", "Students[2].name":"Tom", "Students[2].age":15}
结果预期如下
{SubmitBy:"SK", Students:[{name:"Jhon", age:"15"},{name:"Sam", age:"16"},{name:"Tom", age:"15"} ]}
答:
1赞
AngYC
4/26/2023
#1
您可以使用像 dot-prop
这样的库来实现这一点,代码如下:
import { setProperty } from 'dot-prop';
const input = {
SubmitBy: 'SK',
'Students[0].name': 'Jhon',
'Students[0].age': '15',
'Students[1].name': 'Sam',
'Students[1].age': '16',
'Students[2].name': 'Tom',
'Students[2].age': 15
};
const output = {};
for (const [key, value] of Object.entries(input)) {
setProperty(output, key, value);
}
console.log(output);
0赞
Rohit Chugh
4/26/2023
#2
const originalData = {"SubmitBy":"SK", "Students[0].name":"Jhon", "Students[0].age":"15", "Students[1].name":"Sam", "Students[1].age":"16", "Students[2].name":"Tom", "Students[2].age":15};
const transformedData = { SubmitBy: originalData.SubmitBy, Students: [] };
for (let i = 0; i < 3; i++) {
const student = {
name: originalData[`Students[${i}].name`],
age: originalData[`Students[${i}].age`].toString(),
};
transformedData.Students.push(student);
}
console.log(transformedData);
评论