简体   繁体   English

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

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

I am using the spread syntax in order to get the current 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

But I want to use object assign instead of spread syntax, seems easy but I don't know how to get the result: 但是我想使用对象分配而不是传播语法,这似乎很简单,但是我不知道如何获得结果:

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() copies properties from one or more objects to a single target object. Object.assign()属性从一个或多个对象复制到单个目标对象。 Since CSSID is an array, it copies the array's properties (the items) to the object. 由于CSSID是数组,因此它将数组的属性(项目)复制到对象。 Since you want an object with the property CSSID, set it as a property of the target object, or one of the sources: 由于您想要一个具有CSSID属性的对象,请将其设置为目标对象的属性或源之一:

CSSID should be a property of an object: 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