繁体   English   中英

更改 JSON 对象的格式

[英]Change the format of JSON object

我有 fetch() 请求显示的 JSON 文件。 这是我从数据库请求时得到的示例:

 [
    {
        "id": 3086206,
        "title": "General specifications"
    },
    {
        "id": 3086207,
        "title": "Features and Facilities"
    },
    {
        "id": 3086208,
        "title": "contacts "
    },
    {
        "id": 3086209,
        "title": "Communication"
    }
]

如您所见,有一个包含 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"
    }
}]

如何更改 JSON 文件? 这就是我从 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')) 

您可以使用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);

如果要动态添加大括号,可以在变量num中定义数字。 或删除条件。

暂无
暂无

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

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