[英]Change the format of JSON object
I have JSON file shown by fetch() request.我有 fetch() 请求显示的 JSON 文件。 This is an example of what I get when I request form the database:这是我从数据库请求时得到的示例:
[
{
"id": 3086206,
"title": "General specifications"
},
{
"id": 3086207,
"title": "Features and Facilities"
},
{
"id": 3086208,
"title": "contacts "
},
{
"id": 3086209,
"title": "Communication"
}
]
As you can see there is an array with 4 objects I want to change it to 1 object that has 4 objects in, like this:如您所见,有一个包含 4 个对象的数组,我想将其更改为包含 4 个对象的 1 个对象,如下所示:
[{
"item1": {
"id": 3086206,
"title": "General specifications"
},
"item2": {
"id": 3086207,
"title": "Features and Facilities"
},
"item3": {
"id": 3086208,
"title": "contacts "
},
"item4": {
"id": 3086209,
"title": "Communication"
}
}]
How can I change the JSON file?如何更改 JSON 文件? This is how I display data from JSON file.这就是我从 JSON 文件显示数据的方式。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount() {
fetch('/json', {
method: 'get',
})
.then(response => response.text())
.then(text => {
let Maindata = JSON.parse(text)
this.setState(state => ({
...state,
data: Maindata
}), () => {
this.reorganiseLibrary()
})
}).catch(error => console.error(error))
}
}
ReactDOM.render(<App />, document.getElementById('Content'))
You could do with Array#reduce
with ES6
Approach您可以使用ES6
方法使用Array#reduce
const arr = [ { "id": 3086206, "title": "General specifications" }, { "id": 3086207, "title": "Features and Facilities" }, { "id": 3086208, "title": "contacts " }, { "id": 3086209, "title": "Communication" } ]; const res = arr.reduce( (acc, item, i) => { acc['item' + (i + 1)] = item; return acc; }, {} ); //for ES6 approach //let res = arr.reduce((a,b,c)=>(a['item'+(c+1)]=b,a),{}) console.log([res]) //unnecessary to use wrap array over the object console.log(res) //i think its enough to call res.item1
const arr = [ { "id": 3086206, "title": "General specifications" }, { "id": 3086207, "title": "Features and Facilities" }, { "id": 3086208, "title": "contacts " }, { "id": 3086209, "title": "Communication" } ] const resultArr = [{}]; arr.map((value,index) => { resultArr[0]['item'+(index+1)] = value}) console.log(resultArr)
let data = [ { "id": 3086206, "title": "General specifications" }, { "id": 3086207, "title": "Features and Facilities" }, { "id": 3086208, "title": "contacts " }, { "id": 3086209, "title": "Communication" } ]; let temp={}; let num = 2; data.forEach((element, index) => { if( num > index){ temp[`item${index+1}`] = element; } }); let output = [temp]; console.log(output);
In variable num you can define the number if you want to add braces dynamically.如果要动态添加大括号,可以在变量num中定义数字。 or remove condition.或删除条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.