admin管理员组文章数量:1425043
I have an objects
usersById: {
1: { name: 'John' },
2: { name: 'Michelle' },
...
}
I want to return the same object, but first populate the object at id=2 with a new property age
, but sticking to immutability.
I would guess it would be something like
return {
...usersById,
...usersById[2].age = 40
}
but I receive an error In this environment the sources for assign MUST be an object. This error is a performance optimization and not spec pliant
.
Alternatively, I would guess it should be something like
return Object.keys(usersById).map(userId => {
if (userId === 2) {
return {
...usersById[2],
...age = 40
}
}
return usersById[userId]
})
but it returns an array and not an object.
I have an objects
usersById: {
1: { name: 'John' },
2: { name: 'Michelle' },
...
}
I want to return the same object, but first populate the object at id=2 with a new property age
, but sticking to immutability.
I would guess it would be something like
return {
...usersById,
...usersById[2].age = 40
}
but I receive an error In this environment the sources for assign MUST be an object. This error is a performance optimization and not spec pliant
.
Alternatively, I would guess it should be something like
return Object.keys(usersById).map(userId => {
if (userId === 2) {
return {
...usersById[2],
...age = 40
}
}
return usersById[userId]
})
but it returns an array and not an object.
Share Improve this question asked Oct 19, 2017 at 16:00 JamgreenJamgreen 11.1k32 gold badges122 silver badges232 bronze badges 3- 1 Map always returns an array, as it's an array method. – evolutionxbox Commented Oct 19, 2017 at 16:01
-
I know, but isn't
reduce
also an array method that could return an object witharr.reduce((accumulator, item) => { ... }, {})
? – Jamgreen Commented Oct 19, 2017 at 16:05 - It's not a tautology. Array methods do not always return an array. I shouldn't have used that as an explanation. – evolutionxbox Commented Oct 19, 2017 at 16:28
2 Answers
Reset to default 7You've got the right idea but the wrong syntax. Try this instead:
return {
...usersById,
2: {
...usersById[2],
age: 40
}
}
Or if the key is dynamic, you can do this:
let key = 2;
return {
...usersById,
[key]: {
...usersById[key],
age: 40
}
}
You can make your own function to return same object with populated values
Simple example:
var usersById = {
1: { name: 'John' },
2: { name: 'Michelle' },
}
usersById = oneLevelDeepAssign(usersById,2,{age:21})
function oneLevelDeepAssign(object, key, objectToAssign){
return Object.assign({},object,{[key]:Object.assign({},object[key],objectToAssign)})
}
console.log(usersById);
本文标签: arraysReturn a new object with some extra properties in JavaScriptStack Overflow
版权声明:本文标题:arrays - Return a new object with some extra properties in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745382095a2656210.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论