Javascript:将两个数组的值映射到新数组中 [英] Javascript: Map values of two arrays in a new array

查看:158
本文介绍了Javascript:将两个数组的值映射到新数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象数组,看起来像这样:

I have two arrays of objects, that look like this:

const data = [
  {
    id: 1,
    condition: 1,
    helpers: [{id: 1, condition: null}, {id: 2, condition: 2}]
  },
  {
    id: 2,
    condition: null,
    helpers: [{id: 1, condition: 1}, {id: 2, condition: null}]
  }
]

const conds = [
  {
    id: 1,
    conditions: {
       rules: ['test', 'foo']
    }
  },
  {
    id: 2,
    conditions: {
       rules: ['#hashtag', 'foo']
    }
  }
]

我想要实现的是,我想用 conds 数组中的值替换 data 数组中的 condition

What I try to achieve is, that I want to replace the condition values of the data array with the ones in the conds array.

我的解决方案效果不佳,看起来像这样:

My solution, which does not work quite well looks like this:

let newArray = [];

data.forEach(obj => {
        conds.forEach(cond => {
            if (obj.condition) {
                if (obj.condition === cond.id) {
                    obj.condition = cond.conditions.rules;
                    newArray.push(obj);
                }
            } else {
                obj.helpers.forEach(h => {
                    if (h.condition && h.condition === cond.id) {
                        h.condition = cond.conditions.rules;
                        newArray.push(obj);
                    }
                });
            }
        })
    });

我觉得我已经很接近解决方案了,因为我的 newArray 包含changes属性,但是不包含helpers中的最后一项,而 condition 属性是还是2.

I feel like I am pretty close to the solution since my newArray contains the changes properties, but not for the last item inside of helpers, whereas the condition property is still 2.

输出应如下所示:

[
  {
     id: 1
     condition: ['test', 'foo'],
     helpers: [{id: 1, condition: null}, {id: 2, condition: ['#hashtag', 'foo']}]
  },
  {
     id: 2
     condition: null,
     helpers: [{id: 1, condition: ['test', 'foo']}, {id: 2, condition: null}]
  },
]

我在这里想念什么?

推荐答案

使其正常工作:

const finalData = data.map(dataItem => {
  dataItem.condition = dataItem.condition ? rulesMap[dataItem.condition] : null;
  dataItem.helpers.map(item => {
    item.condition = item.condition ? rulesMap[item.condition] : null
  })
  return dataItem;
});

这篇关于Javascript:将两个数组的值映射到新数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆