1

I have an array and an object that has an array as one of its keys. I want to use Lodash to merge the array into the object replace its array. Here is the code...

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
   }
 ]
}

What I want to do is have the booleans in array1 replace the "checked" booleans in the users array in object1. I want to use Lodash to do this since it seems like it would be much easier, but if there's another way, I'm open to that.

Any suggestions?

2
  • "I want to use Lodash to do this since it seems like it would be much easier" why can you not use a simple loop? Commented Nov 22, 2021 at 21:37
  • A simple loop will suffice Commented Nov 22, 2021 at 21:49

2 Answers 2

3

Given that the arrays are of the same length, you can do this using Array#forEach (or _.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);

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. This works, but can you rewrite it so that array1 is changed with the values in object1? In other words, reverse what you did. I'm having a hard time figuring out how to do that.
You can do this: array1.forEach((_, i, arr) => arr[i] = object1.users[i].checked);
The answer solves the problem, but it doesn't fix the larger issue I'm having with Reactive Forms in Angular 11.
@CodeJunkie this is out of the question's scope. You can post another question targeted towards angular use case..
Thanks for your help Majed!
0

Majed's answer is correct. I'm adding this code here just in case you need to deal with immutability and requires to create new object to trigger changes.

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.