[英]Find property then replace all its values - lodash
I have an array of objects: 我有一个对象数组:
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"wrong"},
{userId: 45, userName:"baz"},
{userId: 56, userName:"..."},
]
Lets say I want to find all objects with the property of userName and replace the value with updatedUser: 假设我想查找所有具有userName属性的对象,并将值替换为updatedUser:
updatedUser = {"foo"}
so in this case I will end up with a new array like: 所以在这种情况下,我将得到一个新的数组,例如:
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"foo"},
{userId: 45, userName:"foo"},
{userId: 56, userName:"foo"}
]
I am using lodash but dont mind native. 我正在使用lodash但不介意原生。
Any help please? 有什么帮助吗?
Why you need lodash, you can do it simply like following. 为什么需要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);
Still if you prefer using lodash
, you can try like following. 不过,如果您更喜欢使用lodash
,可以尝试以下操作。
_.setProperty( users, 'userName', 'foo' );
You could assign a new object with the wanted value. 您可以分配一个具有所需值的新对象。
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);
you can users Array.prototype.map
and override the userName field for each element 您可以使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.