Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS:替换数组中特定对象的某些字段_Javascript_Ecmascript 6 - Fatal编程技术网

Javascript JS:替换数组中特定对象的某些字段

Javascript JS:替换数组中特定对象的某些字段,javascript,ecmascript-6,Javascript,Ecmascript 6,我得到了一个如下所示的对象数组: const items = [ {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"} {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "default"} ] const changeThis = { _id:

我得到了一个如下所示的对象数组:

const items = [
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "default"}
]
const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info" }
注意:项目是只读的,因为它来自react组件中的prop

我想通过一个给定的对象来更新内容,如下所示:

const items = [
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "default"}
]
const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info" }
因此,具有匹配ID的对象应获取“info”作为新上下文值,同时保留所有其他元素:

[
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "info"}
]
另一个例子

而且

const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info", content: "new" }
…应更改匹配对象的上下文和内容:

[
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "new", context: "info"}
]
我的尝试

因此,首先我将使用
map()
遍历数组,但是如何使用
changeThis
-object更新所有其他字段呢? 我试图使用
assign()
keys()
并试图忽略_id-key:

items.map((item, index) => {
  if (item._id === changeThis._id) {
    Object.assign(
      {},
      ...Object.keys(item).map(k => (
        {
          [k]: changeThis.indexOf(k) > -1 && k !== '_id'
            ? changeThis[k]
            : item[k]
        }
    ))
  }
});

一个简单的函数就足够了;请记住,对于
项目
,您需要使用
let
var
而不是
const
;map不会就地编辑,而是返回一个新数组。你可以就地编辑,但我不一定推荐

items = items.map(item => {
  return (item._id === changeThis._id) ?
    { ...item, ...changeThis } :
    item
});

通过将
更改此
的内容扩展到
的键后的对象中,出现在
更改此
中的任何键都将覆盖
中的键。键来自任何一个对象的非重复键也将出现在最终结果中。

为什么不
如果(..)对象。分配(项,更改此)
?一行带。。。四行?;)我把它写在一行里,然后意识到它根本不可读。。。我会编辑的,谢谢