繁体   English   中英

使用 JavaScript 创建 JSON 数组

[英]Creating JSON array using JavaScript

我需要一些帮助。 此代码给出了预期的结果,但当 Id 的值不是整数时失败

const obj = {
    "id": "[1, 2, 3]",
    "priority": "High",
    "assignto": "DanTest",
    "comment": "This is a test"
};

const result = JSON.parse(obj.id).map(e => {
  const copy = {...obj};
  delete copy.id;
  return {
    id: e,
    ...copy
  };
})
console.log(result);

结果:

[
  {
    "id": 1,
    "priority": "High",
    "assignto": "DanTest",
    "comment": "This is a test"
  },
  {
    "id": 2,
    "priority": "High",
    "assignto": "DanTest",
    "comment": "This is a test"
  },
  {
    "id": 3,
    "priority": "High",
    "assignto": "DanTest",
    "comment": "This is a test"
  }
]

如果失败

const obj = {
    "id": "[Jay, Dan, Boy]",
    "priority": "High",
    "assignto": "DanTest",
    "comment": "This is a test"
};

这将返回一个错误:

语法错误:JSON.parse () 位置 1 处的 JSON 中出现意外标记 j

所以从技术上讲,因为id看起来像一个数组,但它是一个string ,你需要先用JSON.parse()解析它,然后使用map()你可以创建一个具有预期结构的新数组。

我想这对你有用:

 const obj = { "id": "[1, 2, 3]", "priority": "High", "assignto": "DanTest", "comment": "This is a test" }; const result = JSON.parse(obj.id).map(e => { const copy = {...obj}; delete copy.id; return { id: e, ...copy }; }) console.log(result);

或者在没有箭头功能的 IE 中:

 const obj = { "id": "[1, 2, 3]", "priority": "High", "assignto": "DanTest", "comment": "This is a test" }; const result = JSON.parse(obj.id).map(function(e) { const copy = {...obj}; delete copy.id; return { id: e, ...copy }; }) console.log(result);

在此处进一步阅读:

  1. Array.prototype.map()
  2. JSON.parse()
  3. 删除操作符

我希望这有帮助!

初始数据

var data = {
    "id": "[ 1, 2, 3]",
    "priority": "High",
    "assignto": "DanTest",
    "comment": "This is a test"
}

解决方案

var newObjList =  [];
// deserialize JSON string to array
var dataConverted = JSON.parse(data.id);
//loop thru ids
for(var i = 0; i < dataConverted.length; i++) {
   //create new object for each id and assign values
   var obj = {
     id: dataConverted[i],
     priority: data.priority,
      assignTo: data.assignTo,
      comment: data.comment
   }
   //add object to a list
   newObjList.push(obj);
}

然后访问您可以将 JSON 序列化为字符串

var jsonString = JSON.stringify(newObjList);

您可以通过以下方式实现此目的:

 let obj = { "id": "[ 1, 2, 3]", "priority": "High", "assignto": "DanTest", "comment": "This is a test" }; let objArr = JSON.parse(obj.id).map((x) => { return { "id": x, "priority": obj.priority, "assignto": obj.assignto, "comment": obj.comment } }); console.log(objArr);

如果您可以访问较新的 ES2015+,您只需执行以下操作即可。

const newJson = oldJson.id.map(id => ({ ...oldJson, id }));

或者在 ES5 中

const newJson = oldJson.id.map(function(id) { 
   return Object.assign({}, oldJson, { id: id });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM