Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new properties of object in lodash

I've two objects and I want to add properties from object A to object B and I try with extend which doesn't work,do I need to use something different ?

a = {
name = "value"
name2 = "value2"
}

b = {
name3 = "value"
name4 = "value2"
}

I want that A will contain both

a = {
name = "value"
name2 = "value2"
name3 = "value"
name4 = "value2"
}
like image 397
07_05_GuyT Avatar asked Aug 30 '15 14:08

07_05_GuyT


People also ask

How do you add a new property to an object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

Do people still use Lodash?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What is Lodash throttle?

throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds.


2 Answers

_.extend (now called _.assign) is indeed how you do this:

_.assign(a, b);

Live Example:

const a = {
    name: "value",
    name2: "value2",
};

const b = {
    name3: "value",
    name4: "value2",
};

_.assign(a, b);
console.log(JSON.stringify(a, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>

Though as of ES2015, you don't need Lodash for it, you can use the native Object.assign:

Live Example:

const a = {
    name: "value",
    name2: "value2",
};

const b = {
    name3: "value",
    name4: "value2",
};

Object.assign(a, b);
console.log(JSON.stringify(a, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
like image 87
T.J. Crowder Avatar answered Sep 23 '22 11:09

T.J. Crowder


First of all, your defined objects are incorrect. Objects must be written as name:value pairs, separated by a colon (and not by an equality sign). Furthermore, you must use comma separators to delimit the properties of the object, like:

var person = {
    firstName: "Matthias",
    lastName: "Eckhart",
    eyeColor: "blue"
};

To extend an object with various properties via lodash, you can use _.assign(object, [sources], [customizer], [thisArg]):

var a = {
  name: "value",
  name2: "value2"
};

var b = {
  name3: "value",
  name4: "value2"
};

_.assign(a, b); // extend

console.log(a);
<script src="https://raw.githubusercontent.com/lodash/lodash/3.10.1/lodash.min.js"></script>
like image 40
Matthias A. Eckhart Avatar answered Sep 23 '22 11:09

Matthias A. Eckhart