如何将多个值存储到数组中的 objects

How to store multiple values in to objects within an array

问题:

我有一个 api,api 中的每个 object 都没有值。我想为数组中的每个 object 添加一个唯一值,以便我可以创建一个函数并将 'e.target.value' 与事件侦听器一起使用。我在 nextjs 中这样做。

为什么: 因为我想在最终将存储在数组中的数据显示为收藏夹项目之前将每个值存储到数组和本地存储中。

有办法吗?

信息:

data.items 超过 30+ objects -

"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
      "owner": {
        "login": "drcmda",
        "id": 2223602,
}

{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
      "owner": {
        "login": "drcmda",
        "id": 2223602,
}

到目前为止,我的数据已经像这样排序和映射了。

{data.items
          .sort(function (a, b) {
            return b.stargazers_count - a.stargazers_count && new Date (b.created_at) - new Date(a.created_at) 
          })
          .map((d) => (
            
            <div onClick={checkId} key={d.id} className=" border-white p-5">
              
              <h1 className="text-2xl font-bold">Repo name: {d.name}</h1>

如果您想为每个对象添加一个 VALUE 键,您可以执行以下操作:

const [isLoading, setIsLoading] = useState(false),
    [items, setItems] = useState([]);

useEffect(() => {
    (async () => {
        setIsLoading(true);
        try {
            //you can replace axios with fetch
            const res = await axios('https://your-api'),
                // clone deep is from lodash => you can use the spread (...) operator if you want
                clonedItems = cloneDeep(res.data.items);

            clonedItems.forEach((el) => {
                // add whatever you want in the (value)
                el.value = 'required value';
            });
            //sort items based on the required key
            clonedItems.sort((a, b) => {
                //replace name with your key
                if (a.name.toLowerCase() < b.name.toLowerCase()) {
                    return -1;
                }
                if (a.name.toLowerCase() > b.name.toLowerCase()) {
                    return 1;
                }
                return 0;
            });
            //check the modified items
            console.log(clonedItems);

            setItems(clonedItems);
        } catch (err) {
            //replace it with your error handler code
            console.log(err);
        } finally {
            setIsLoading(false);
        }
    })();
}, []);

备注:

  • 您应该先对元素进行排序,然后再将其存储在状态中
  • 你可以用 fetch 代替 axios
  • 您可以使用扩展运算符 (...) 代替 lodash 中的 cloneDeep

使用索引作为显示目的的唯一示例。

const data = {
    items: [
        {
            id: 119603782,
            node_id: "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
            name: "react-contextual",
            full_name: "drcmda/react-contextual",
            private: false,
            owner: {
                login: "drcmda",
                id: 2223602,
            },
        },
        {
            id: 119603782,
            node_id: "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
            name: "react-contextual",
            full_name: "drcmda/react-contextual",
            private: false,
            owner: {
                login: "drcmda",
                id: 2223602,
            },
        },
    ],
};

const items = data.items.map((item, idx) => ({ ...item, idx }));

// new item
const newItem = {
    id: 119603782,
    node_id: "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
    name: "react-contextual",
    full_name: "drcmda/react-contextual",
    private: false,
    owner: {
        login: "drcmda",
        id: 2223602,
    },
};

function addNewItems(items, newItem) {
    newItem.idx = items.length;
    items.push(newItem);
    return items;
}

console.log(addNewItems(items, newItem));