【问题标题】:Merge array into an array of an objects将数组合并为对象数组
【发布时间】:2022-01-01 11:01:42
【问题描述】:

我有一个数组和一个以数组作为键之一的对象。我想使用 Lodash 将数组合并到对象中替换它的数组。这是代码...

array1 = [false, true, true];

object1 = {
 id: 1,
 label: 'lorem',
 description: "ipsum",
 users: [
   {
     id: 1,
     user: 'morbi',
     checked: true
   },
   {
     id: 2,
     user: 'mauris',
     checked: true
   },
   {
     id: 3,
     user: 'duis',
     checked: true
   }
 ]
}

我想要做的是让 array1 中的布尔值替换 object1 中用户数组中的“已检查”布尔值。我想使用 Lodash 来执行此操作,因为它看起来会更容易,但如果有其他方法,我愿意。

有什么建议吗?

【问题讨论】:

  • "我想用 Lodash 来做这件事,因为它看起来会容易得多"为什么你不能使用简单的循环?
  • 一个简单的循环就足够了

标签: javascript arrays object replace lodash


【解决方案1】:

鉴于数组的长度相同,您可以使用Array#forEach(或_.forEach)来做到这一点:

const 
  array1 = [false, true, true],
  object1 = {
    id: 1,
    label: 'lorem',
    description: "ipsum",
    users: [
      { id: 1, user: 'morbi', checked: true },
      { id: 2, user: 'mauris', checked: true },
      { id: 3, user: 'duis', checked: true }
   ]
};

object1.users.forEach((user, i) => user.checked = array1[i]);

console.log(object1.users);

【讨论】:

  • 谢谢。这行得通,但是您可以重写它,以便用 object1 中的值更改 array1 吗?换句话说,扭转你所做的。我很难弄清楚该怎么做。
  • 你可以这样做:array1.forEach((_, i, arr) => arr[i] = object1.users[i].checked);
  • 答案解决了问题,但并不能解决我在 Angular 11 中使用反应式表单时遇到的更大问题。
  • @CodeJunkie 这超出了问题的范围。您可以发布另一个针对角度用例的问题..
  • 感谢 Majed 的帮助!
【解决方案2】:

Majed 的回答是正确的。 我在此处添加此代码,以防您需要处理不变性并需要创建新对象来触发更改。

const 
  array1 = [false, true, true],
  object1 = {
    id: 1,
    label: 'lorem',
    description: "ipsum",
    users: [
      { id: 1, user: 'morbi', checked: true },
      { id: 2, user: 'mauris', checked: true },
      { id: 3, user: 'duis', checked: true }
   ]
};

function updateAnswer(obj, answers) {
  return {
    ...obj,
    users: obj.users.map((user, index) => {
      return { ...user, checked: answers[index] }
    })
  }
}

console.log(updateAnswer(object1, array1));

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多