[英]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上玩的示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.