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 with arr.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
Add a ment  | 

2 Answers 2

Reset to default 7

You'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