繁体   English   中英

如何在数据和对象数组的合并中使用对象分配而不是传播语法?

[英]How to use object assign instead of spread syntax in merge of array of data and object?

我正在使用传播语法以获取当前对象。

const x = [{ port: 3000, typ: "port" }, { port: 4000, typ: "port" }];
const IDs = [3246237348, 738423894, 73824923]
const y = {
  ...x[0],
  CSSID
};

Object {port: 3000, typ: "port", CSSID: Array[3]}
  port: 3000
  typ: "port"
  CSSID: Array[3]
     0: 3246237348
     1: 738423894
     2: 73824923

但是我想使用对象分配而不是传播语法,这似乎很简单,但是我不知道如何获得结果:

const ob = Object.assign(Object.assign({}, x[0], Object.assign(CSSID)) );

Object {0: 3246237348, 1: 738423894, 2: 73824923, port: 3000, typ: "port"}
    0: 3246237348
    1: 738423894
    2: 73824923

Object.assign()属性从一个或多个对象复制到单个目标对象。 由于CSSID是数组,因此它将数组的属性(项目)复制到对象。 由于您想要一个具有CSSID属性的对象,请将其设置为目标对象的属性或源之一:

CSSID应该是对象的属性:

 const x = [{ port: 3000, typ: "port" }, { port: 4000, typ: "port" }]; const CSSID = [3246237348, 738423894, 73824923]; const ob = Object.assign({}, x[0], { CSSID }); // or Object.assign({ CSSID }, x[0]); console.log(ob); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM