如何将具有数组索引的对象解析为具有键值对的对象数组

How to parse an objects with array index to object array with key value pairs

提问人:Shankar Kumar 提问时间:4/26/2023 最后编辑:Shankar Kumar 更新时间:10/18/2023 访问量:76

问:

将此对象 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"} ]}
数组 数组列出 JavaScript 对象

评论

0赞 pilchard 4/26/2023
duplicate:Javascript:将点分隔的字符串转换为嵌套对象值
0赞 pilchard 4/26/2023
点分隔字符串数组中的树

答:

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); 

评论

0赞 Community 4/27/2023
正如目前所写的那样,你的答案尚不清楚。请编辑以添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以在帮助中心找到有关如何写出好答案的更多信息。