How to use the toPlainObject function from lodash

Find comprehensive JavaScript lodash.toPlainObject code examples handpicked from public code repositorys.

lodash.toPlainObject creates an object with keys and values derived from the given object.

393
394
395
396
397
398
399
400
401
402
module.exports.toLower             = _.toLower;
module.exports.toNumber            = _.toNumber;
module.exports.toPairs             = _.toPairs;
module.exports.toPairsIn           = _.toPairsIn;
module.exports.toPath              = _.toPath;
module.exports.toPlainObject       = _.toPlainObject;
module.exports.toQuery             = _.toQuery;
module.exports.toSafeInteger       = _.toSafeInteger;
module.exports.toString            = _.toString;
module.exports.toUpper             = _.toUpper;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

521
522
523
524
525
526
527
528
529
530
531
532
533
console.log(toLength); // => 3


const toNumber = _.toNumber('3.2');
console.log(toNumber); // => 3.2


const toPlainObject = _.toPlainObject([1, 2, 3]);
console.log(toPlainObject); // => { '0': 1, '1': 2, '2': 3 }


const toSafeInteger = _.toSafeInteger(3.2);
console.log(toSafeInteger); // => 3
fork icon0
star icon4
watch icon0

+ 15 other calls in file

How does lodash.toPlainObject work?

lodash.toPlainObject creates a plain object from an object that is inherited from a prototype. It creates a new object with its own properties only and not the inherited ones. If the object is already a plain object with no inherited properties, it returns the object itself. Internally, lodash.toPlainObject uses Object.create(null) method to create a new object with no prototype, hence it doesn't inherit any properties from the prototype chain. It then copies all the own enumerable string keyed properties from the original object to the newly created plain object. This ensures that the returned object has only its own properties and doesn't contain any properties inherited from its prototype chain.

Ai Example

1
2
3
4
5
6
const obj = Object.create({ foo: 1 });
obj.bar = 2;

const plainObj = _.toPlainObject(obj);

console.log(plainObj); // { bar: 2 }

In this example, lodash.toPlainObject is used to create a plain object from the given object obj. obj is created using Object.create() and has a property bar with the value 2. When lodash.toPlainObject is called with obj as the argument, it returns a new object with the same properties and values as obj, but without the foo property inherited from the prototype. Finally, the resulting plain object is logged to the console.

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)