简体   繁体   中英

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. Since CSSID is an array, it copies the array's properties (the items) to the object. Since you want an object with the property CSSID, set it as a property of the target object, or one of the sources:

CSSID should be a property of an object:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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