繁体   English   中英

如何像值一样更改Json格式将是对象名称

[英]How to change Json format like a value will be object name

如何从波纹管形式设置json文件:我喜欢将id值设置为对象名称。

[{
  "id": 1,
  "public_name": "Duygu D.",
  "professions": "Kumas dizayn",
  "job_preference": "freelancer"
}, {
  "id": 2,
  "public_name": "Meral A.",
  "professions": "Model Uyg.",
  "job_preference": "freelancer"
}]

至以下表格:

{
  "1": {
    "public_name": "Duygu D.",
    "professions": "Kumas dizayn",
  },
  "2": {
    "public_name": "Meral A.",
    "professions": "Model Uyg.",
  }
}

 var arr = [{ "id": 1, "public_name": "Duygu D.", "professions": "Kumas dizayn", "job_preference": "freelancer" }, { "id": 2, "public_name": "Meral A.", "professions": "Model Uyg.", "job_preference": "freelancer" }]; var newObj = {}; arr.forEach(function(el){ newObj[el.id] = {public_name: el.public_name, professions: el.professions}; }); console.log(newObj); 

newObj将是您想要的对象

遍历数组,并使用所需数据将新属性添加到空对象result

 var data = [{ "id": 1, "public_name": "Duygu D.", "professions": "Kumas dizayn", "job_preference": "freelancer" }, { "id": 2, "public_name": "Meral A.", "professions": "Model Uyg.", "job_preference": "freelancer" }]; var result = {}; data.forEach(function(item){ result[item.id] = { "public_name" : item.public_name, "professions" : item.professions }; }); console.log(result); 

您可以使用Array的reduce()方法。

var arr = [{
  "id": 1,
  "public_name": "Duygu D.",
  "professions": "Kumas dizayn",
  "job_preference": "freelancer"
}, {
  "id": 2,
  "public_name": "Meral A.",
  "professions": "Model Uyg.",
  "job_preference": "freelancer"
}];

var obj = arr.reduce(function(o, v, i) {
  o[v.id] = {"public_name":v.public_name,  "professions": v.professions};
  return o;
}, {});

尝试这样的事情:

// Your original array of objects stored in a variable.
const originalObject = [{
  "id": 1,
  "public_name": "Duygu D.",
  "professions": "Kumas dizayn",
  "job_preference": "freelancer"
}, {
  "id": 2,
  "public_name": "Meral A.",
  "professions": "Model Uyg.",
  "job_preference": "freelancer"
}];

// Create an empty new object to hold your new format.
const newObject = {};

// Loop the original object.
originalObject.forEach(item => {
  // Create a key in the new object based on the id of the original object.
  // Warning: This assumes your id's are unique.
  newObject[item.id] = { 
    public_name: item.public_name,
    professions: item.professions
  };
});

// Convert the object to a JSON string (optional).
const jsonString = JSON.stringify(newObject);

console.log(`As JS object ${newObject} or as JSON string ${jsonString}`);

该代码为ES6,但可以轻松转换为ES5。

这是您可以在Codepen上玩的示例:

http://codepen.io/anon/pen/WozoLo?editors=0010#0

暂无
暂无

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

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