在React中更新数组中的元素(使用filter / map)

时间:2019-09-11 05:59:29

标签: javascript jquery reactjs

我有一个具有以下结构的数组:

this.state.mainArray= [{
    "Upperelement1": "12345",
    "Upperelement2" : [
        {
          Key1:'ok1',Key2:'ok2',Key3:'ok3'
        },
        {
          Key1:'ok4',Key2:'ok6',Key3:'ok7'
        },
        ]
    },
    {
    "Upperelement1": "6789",
    "Upperelement2" : [
        {
          Key1:'ok8',Key2:'ok9',Key3:'o10'
        },
        {
          Key1:'ok11',Key2:'ok12',Key3:'ok13'
        },
        ]
     }
    ]

想法将遍历数组并在Upperelement1 = 12345Key1:'ok1'(键的值是唯一的)中找到元素 并向Upperelement2key4添加另一个密钥。更新后,数组将如下所示:

  [{
    "Upperelement1": "12345",
    "Upperelement2" : [
        {

        Key1:'ok1',Key2:'ok2',Key3:'ok3',Key4:'somevalue'
        },
        {
          Key1:'ok4',Key2:'ok6',Key3:'ok7'
        },
        ]
    },
    {
    "Upperelement1": "6789",
    "Upperelement2" : [
        {
          Key1:'ok8',Key2:'ok9',Key3:'o10'
        },
        {
          Key1:'ok11',Key2:'ok12',Key3:'ok13'
        },
        ]
     }
    ]

我尝试了类似的方法:

mainArray.map(items => if (items. Upperelement1 == '12345')
  • 但是那行不通, 有什么想法可以实现吗? 我们可以使用过滤器吗?

3 个答案:

答案 0 :(得分:2)

您可以使用find()some()map()来做到这一点。

var data = [{ Upperelement1: "12345", Upperelement2: [{ Key1: "ok1", Key2: "ok2", Key3: "ok3" }, { Key1: "ok4", Key2: "ok6", Key3: "ok7" }, ] }, { Upperelement1: "6789", Upperelement2: [{ Key1: "ok8", Key2: "ok9", Key3: "o10" }, { Key1: "ok11", Key2: "ok12", Key3: "ok13" }, ] } ]; 

data.find(item =>
    item.Upperelement1 === "12345" &&
    item.Upperelement2.some(value => value.Key1 === "ok1")
  )
  .Upperelement2.map(item => {
    if (item.Key1 === "ok1") {
      item["Key4"] = "somevalue";
    }
    return item;
  });

console.log(data);

答案 1 :(得分:1)

您可以使用2张地图

const newValues = mainArray.map((item) => {
  if (item.Upperelement1 !== '12345') {
    return item
  }

  return {
      ...item,
      Upperelement2: item.Upperelement2.map(upper => {
        if(upper.Key1 !== 'ok1') {
          return upper 
        }

        return {
          ...upper,
          Key4:'somevalue',
        }
      })
    }
})

答案 2 :(得分:1)

我认为使用这样的嵌套map很简单

arr.map(function(item){
   if (item.Upperelement1 === '12345'){
        return {
            Upperelement1: item.Upperelement1,
            Upperelement2: item.Upperelement2.map(function(obj){
                if (obj.Key1 === 'ok1'){
                    return Object.assign({}, obj, { Key4: 'somevalue'});
                }
                return obj;
            })
        };
   }
    return item;
})