我有一个对象数组:
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"wrong"},
{userId: 45, userName:"baz"},
{userId: 56, userName:"..."},
]
让我们说我想找到所有具有userName属性的对象,并将值替换为updatedUser:
updatedUser = {"foo"}
所以在这种情况下,我将得到一个新的数组,例如:
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"foo"},
{userId: 45, userName:"foo"},
{userId: 56, userName:"foo"}
]
我正在使用lodash,但不介意原生。
请帮忙吗?
答案 0 :(得分:0)
为什么需要lodash,您可以按照以下步骤操作。
users.forEach((el)=>{el.userName= "foo";})
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"wrong"},
{userId: 45, userName:"baz"},
{userId: 56, userName:"..."}
]
users.forEach((el)=>{el.userName = "foo";})
console.log(users);
仍然,如果您更喜欢使用lodash
,可以尝试以下操作。
_.setProperty( users, 'userName', 'foo' );
答案 1 :(得分:0)
您可以分配一个具有所需值的新对象。
var users = [{ userId: 23, userName: "foo" }, { userId: 34, userName: "wrong" }, { userId: 45, userName: "baz" }, { userId: 56, userName: "..." }],
update = { userName: "foo" },
result = users.map(o => Object.assign({}, o, update));
console.log(result);
答案 2 :(得分:0)
您可以为用户Array.prototype.map
并为每个元素覆盖userName字段
const users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"wrong"},
{userId: 45, userName:"baz"},
{userId: 56, userName:""}
];
const result = users.map(u => ({...u, userName: "foo"}));
console.log(result);