【发布时间】:2020-08-01 11:07:05
【问题描述】:
我有一个 Json,兴趣键值是字符串,如何处理它并获得我的预期输出。 包含的文件是实际数据。在这里我无法传递键值 这是我的代码
const arr = [];
const file = [
{
name: "same",
hobby: '{ "name": "music", "type": "jazz" }'
},
];
file.forEach((item) => {
Object.keys(JSON.parse(item.hobby)).forEach((key) => {
const base = { ...item, hobby_name: "", hobby_type: "" };
base.hobby_name= key;
base.hobby_type= base.hobby_type[key];
arr.push(base);
});
});
console.log(arr);
输出:
[
{
name: "sam",
content: '{ "h_name": "music", "h_type": "jazz" }',
content1: "h_name"
constent2: ""
},
{
name: "sam",
content: '{ "h_name": "music", "h_type": "jazz" }',
content1: "h_type"
constent2: ""
},
];
预期输出:
[
{
name: "sam",
content: '{ "h_name": "music", "h_type": "jazz" }',
content1: "h_name"
constent2: "music"
},
{
name: "sam",
content: '{ "h_name": "music", "h_type": "jazz" }',
content1: "h_type"
constent2: "jazz"
},
];
【问题讨论】: