今天,我遇到了一个问题,即替换对象数组中的匹配对象.
为此,他们使用lodash在对象数组中找到匹配对象的索引.
var users = [{user: "Kamal"}, {user: "Vivek"}, {user: "Guna"}]
var idx = _.findIndex(users, {user: "Vivek"}); // returns 1
Run Code Online (Sandbox Code Playgroud)
现在他们使用splice()代替这样,
users.splice(idx, 1, {user: "Gowtham"})
Run Code Online (Sandbox Code Playgroud)
但为什么不呢,
users[idx] = {user: "Gowtham"};
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,有没有理由,不这样做或使用splice()?
因为它使用起来非常简单array[index] = 'something';.不是吗?
我有以下对象数组:
var arr = [
{
id : "a1",
guid : "sdfsfd",
...
value : "abc",
status: "active"
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def",
status: "inactive"
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def"
},
...
]
Run Code Online (Sandbox Code Playgroud)
如何将每个对象的"status"属性设置为"active".因此得到的数组将是:
var arr = [
{
id : "a1",
guid : "sdfsfd",
...
value : "abc",
status: "active"
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def",
status: …Run Code Online (Sandbox Code Playgroud) 有没有一种简单的方法可以将数组中基元的所有外观替换为另一个基元.所以这['a', 'b', 'a', 'c']将成为['x', 'b', 'x', 'c']更换时a用x.我知道这可以通过map函数完成,但我想知道是否忽略了一种更简单的方法.