繁体   English   中英

在数组中添加数据数组的最佳方法是什么?

[英]What is the best way to add data array in an array?

我有一个 state object ,其中有一个类别数组。 在这个对象数组中,object 的一个键(“列表”)被分配了一个数组。 我需要做的是

  1. 按名称过滤类别数组中的特定 object
  2. 将新的 object 添加到过滤后的 object 的“列表”属性(数组)(保留旧的)

例子

const initialState = {
    category: [
        {
            name: "new",
            color: "#5236C1",
            list: [
                {
                    title: "name title",
                    about: "about",
                    imgLink: 'https://www.google.com/s2/favicons?domain=https://mail.yandex.ru/',
                    url: 'https://www.yandex.ru'
                }, 
                 // there should be a new object
            ]
        },

试图这样做

const addBM = (state, payload) => {
    console.log(payload)
    const {url, title, about, cat} = payload
    let selectCatArr = state.category.filter((item) => item.name == cat)
    return {
        ...state,
        category: [...state.category, {list: [title, url, about ]}]
    }
}

应该有一个新的 object

我修改了 addBM function 并添加了一些解释代码的注释。

const addBM = (state, payload) => {
    console.log(payload)
    const {url, title, about, cat} = payload

    // use map method instead of filter
    const modifiedCategory = state.category.map(categoryItem => {
        // only modify the category item if it's name matches the cat argument
        // otherwise return the original category item
        
        if (categoryItem.name == cat) {
            // create a copy of the category item object
            let modifiedCategoryItem = {
                ...categoryItem,
                // modify the list array of this object by
                // creating a copy of the array and
                // adding a new object with (url, title and about arguments) in this array
                list: [...categoryItem.list, {url, title, about}]
            };
            return modifiedCategoryItem;
        } else {
            return categoryItem;
        }
    });

    return {
        ...state,
        category: modifiedCategory
    }
};

暂无
暂无

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

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