简体   繁体   English

如何从对象数组创建一个新的 object?

[英]How to create a new object from array of objects?

I have the following dynamic array of objects:我有以下动态对象数组:

[

{
id: "1"
name: "Jane"
age: 25
},

{
id: "2"
name: "John"
age: 35
},

{
id: "3"
name: "James"
age: 27
},
]

I need to create new object like this:我需要像这样创建新的 object:

"peopleSelected:{

"1":
{
"name": "Jane",
"age": 25
},

"2":
{
"name": "John",
"age": 35
},

"3":
{
"name": "James",
"age": 27
},

where structure is结构在哪里

"id" :
{
"name":name,
"age":"age
}

and I need to save this newly created object using useState, I can't figure out how to do that.我需要使用 useState 保存这个新创建的 object,我不知道该怎么做。 Please help.请帮忙。

Using Array.prototype.reduce()使用Array.prototype.reduce()

 const arr = [ { id: "1", name: "Jane", age: 25, }, { id: "2", name: "John", age: 35, }, { id: "3", name: "James", age: 27, }, ], solution = { peopleSelected: arr.reduce((acc, { id, name, age }) => { acc[id] = { name, age }; return acc; }, {}), }; console.log(solution);

You can use object destructuring as below:您可以使用 object 解构如下:

import React from 'react';
import { useState, useEffect } from 'react';

let people = [
    {
        id: "1",
        name: "Jane",
        age: 25
    },
    {
        id: "2",
        name: "John",
        age: 35
    },
    {
        id: "3",
        name: "James",
        age: 27
    }
];

function App() {
    const [ selectedPeople, setSelectedPeople ] = useState({});

    useEffect(() => {
        console.log(Object.entries(people));
        let extractedArray = Object.entries(people);
        let result = extractedArray.map((item) => {
          return `${item[1].id}: ${{
            "name": item[1].name,
            "age": item[1].age
          }}`
        })
        console.log(result);
        
        // Performing object destructuring and setting the state of selectedPeople as an object
        setSelectedPeople({...people})
    }, [])

    return <div>
        <pre>
            {JSON.stringify(selectedPeople, null, '\t')}
        </pre>
    </div>;
}

export default App;

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

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