【问题标题】:How to map array of object with another array in react or javascript?如何在反应或javascript中将对象数组与另一个数组映射?
【发布时间】:2020-07-21 05:59:20
【问题描述】:
const arrayObj = [{
        id: 123,
        country: "IND"
        value: ""
    },
    {
        id: 153,
        country: "AUS"
        value: ""
    },
    {
        id: 183,
        country: "FRA"
        value: ""
    }
];

const value = [100, 200, 300];

我需要将值数组映射到对象数组中对应的值属性

所以,我的对象数组看起来像这样

[
    {
        id: 123,
        country: "IND"
        value: 100
    },
    {
        id: 153,
        country: "AUS"
        value: 200
    },
    {
        id: 183,
        country: "FRA"
        value: 300
    }
]

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    您可以映射arrayObj 并使用索引参数从value 数组中获取相应的值。

    const arrayObj = [
      {
        id: 123,
        country: "IND",
        value: "",
      },
      {
        id: 153,
        country: "AUS",
        value: "",
      },
      {
        id: 183,
        country: "FRA",
        value: "",
      },
    ];
    
    const value = [100, 200, 300];
    
    const result = arrayObj.map((item, index) => ({...item, value: value[index]}));
    console.log(result);
    
    // If you don't want to create new array, you can use forEach
    arrayObj.forEach((item, index) => {
        item.value = value[index];
    });

    【讨论】:

      【解决方案2】:

      首先你必须将每个对象格式化为arrayObj变量,数组中的项目由,分隔,就像[1,2,3]一样,每个@都一样987654324@ 对象中的对 {item1: "itemvalue", item2: "itemvalue2"}

      const arrayObj = [{
              id: 123,
              country: "IND",
              value: ""
          },
          {
              id: 153,
              country: "AUS",
              value: ""
          },
          {
              id: 183,
              country: "FRA",
              value: ""
          }
      ];
      const value = [100, 200, 300];
      
      const newArrayObj = arrayObj.reduce((acc, current, index) => {
          return acc.concat({...current, value: value[index]}); 
      }, []);
      
      console.log(newArrayObj);

      【讨论】:

        猜你喜欢
        • 2020-11-22
        • 1970-01-01
        • 2020-07-29
        • 2021-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-31
        相关资源
        最近更新 更多