[英]Extend an object without destroying nested object attributes?
I have an object with some nested objects, I want to extend the object and in some cases the nested objects will be returned as empty although I'd like to preserve these - can anyone recommend how I can do this? 我有一个带有一些嵌套对象的对象,我想扩展该对象,在某些情况下,尽管我想保留这些嵌套对象,但它们将返回为空-有人可以推荐我该怎么做吗?
let myObject = {
id: 1,
configs: {
track: true,
pulse: false
},
name: 'slider',
position: 1
}
let updatedObject = Object.assign({}, myObject, {
name: 'scroller',
configs: {}
})
// outputs {id: 1, configs: {}, name: 'scroller', position: 1}
found this useful plugin https://www.npmjs.com/package/deepmerge 发现了这个有用的插件https://www.npmjs.com/package/deepmerge
You can use _.merge()
method from Lodash. 您可以使用
_.merge()
方法。
let myObject = { id: 1, configs: { track: true, pulse: false }, name: 'slider', position: 1 } var update = _.merge({}, myObject, { name: 'scroller', configs: {} }) console.log(update)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
let myObject = { id: 1, configs: { track: true, pulse: false }, name: 'slider', position: 1 } let updatedObject = shallowAssignNonEmptyProperties(Object.assign({}, myObject), { name: 'scroller', configs: {} })) function shallowAssignNonEmptyProperties(target, source) { for (const prop in source) { const newValue = source[prop] if (typeof newValue !== 'object' || Object.keys(newValue).length) { target[prop] = newValue } } }
When we want to skip specific properties, Object.assign()
or object spread
won't work. 当我们想跳过特定属性时,
Object.assign()
或object spread
将不起作用。 If you want to come up with a solution, it requires to iterate the properties, inspect the type of them and decide if you want that value to be assigned over. 如果要提出解决方案,则需要迭代属性,检查属性的类型,然后确定是否要分配该值。
typeof newValue !== 'object'
: we let pass values other than objects; typeof newValue !== 'object'
:我们传递对象以外的值; Object.keys(newValue).length
: check if the object is empty or have any properties; Object.keys(newValue).length
:检查对象是否为空或具有任何属性; This one is pretty simple, although if you need deep assignment/merge, you'll use a lib (lodash) or recursively call this function. 这很简单,尽管如果需要深度分配/合并,则可以使用lib(破折号)或递归调用此函数。 It's up to you.
由你决定。
Nested properties are used as-is, they are not recursively assigned/merged. 嵌套属性按原样使用,不会递归分配/合并它们。 So the
configs
object is taken from the final argument of the assign(...)
call (which is an empty object) and completely overrides the earlier values. 因此
configs
对象取自assign(...)
调用的最后一个参数(它是一个空对象),并且完全覆盖了先前的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.