[英]I want to simplify (using Object.assign) a batch of JSON file
I have a batch of JSON files looking like this:我有一批看起来像这样的 JSON 文件:
{
"properties": [
{
"Frame": "Yellow"
},
{
"Sky": "Apocalypse"
},
{
"Grass": "green"
},
{
"Sign": "sign"
},
{
"Graffitis": "shit"
},
{
"Things": "can"
},
{
"Quotes": "emptyness"
},
{
"Border": "framing"
},
{
"Logo": "logo"
},
{
"Overlay": "overlay"
}
]
}
And I want to modify them so they look like this:我想修改它们,使它们看起来像这样:
{
Border: "framing",
Frame: "Yellow",
Graffitis: "shit",
Grass: "green",
Logo: "logo",
Overlay: "overlay",
Quotes: "emptyness",
Sign: "sign",
Sky: "Apocalypse",
Things: "can"
}
How can I achieve this?我怎样才能做到这一点?
Use Object.assign like so像这样使用Object.assign
const input = {
"properties": [
{
"Frame": "Yellow"
},
{
"Sky": "Apocalypse"
},
{
"Grass": "green"
},
{
"Sign": "sign"
},
{
"Graffitis": "shit"
},
{
"Things": "can"
},
{
"Quotes": "emptyness"
},
{
"Border": "framing"
},
{
"Logo": "logo"
},
{
"Overlay": "overlay"
}
]
}
const output = Object.assign({}, ...input.properties);
You can use Array.prototype.reduce()
and spread syntax to accomplish this in one line:您可以使用
Array.prototype.reduce()
和传播语法在一行中完成此操作:
let obj = { "properties": [{ "Frame": "Yellow" }, { "Sky": "Apocalypse" }, { "Grass": "green" }, { "Sign": "sign" }, { "Graffitis": "shit" }, { "Things": "can" }, { "Quotes": "emptyness" }, { "Border": "framing" }, { "Logo": "logo" }, { "Overlay": "overlay" }] } console.log(obj["properties"].reduce((prev, current) => ({...prev, ...current }), {}))
Hey and welcome to StackOverflow!嘿,欢迎来到 StackOverflow!
I recommend using a for-loop to iterate through an object you have parsed from the json ( JS read json file and use as an object ):我建议使用 for 循环遍历您从 json 解析的 object( JS 读取 json 文件并用作 ZA8CFDE6331BD59EB2AC96F8911C4B6669 )
let newObject = {};
properties.forEach(property => {
Object.assign(newObject, property);
}
return newObject;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.