Home > other >  how to access and assign new value in array/object in lodash
how to access and assign new value in array/object in lodash

Time:02-17

I am looking for simple easy way to assign new value through lodash. See the blow example. I only want to reassign value of first element of object of first element of arr array.

const arr = [
 {
   a: 'apple',
   b: 'banana',
   c: 'cat'
 },
 {
   a: 'apple-1',
   b: 'banana-2',
   c: 'cat-3'
 }
];

const newArr = arr;
const ele = ._first(newArr);// picked first element
ele['a'] = 'dog';

this is what I expect to see

console.log(newArr);
// [
 {
   a: 'dog', //<--- updated
   b: 'banana',
   c: 'cat'
 },
 {
   a: 'apple-1',
   b: 'banana-2',
   c: 'cat-3'
 }
];

thank you ahead!

CodePudding user response:

Why you cannot just use simple JS without lodash?

const arr = [
 {
   a: 'apple',
   b: 'banana',
   c: 'cat'
 },
 {
   a: 'apple-1',
   b: 'banana-2',
   c: 'cat-3'
 }
];

const newArr = arr;
newArr[0].a = 'dog'

console.log(arr)

  • Related