Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

รวมออบเจ็กต์และลบคุณสมบัติด้วย JavaScript


เรามีอาร์เรย์ออบเจ็กต์ 2 ตัว ต้องรวมเป็นออบเจ็กต์เดียวและลบคุณสมบัติ chk ออกไปทั้งหมด −

const err = [    {       "chk" : true,       "name": "test"    },    {       "chk" :true,       "post": "test"    } ];

ขั้นตอน 1 − รวมออบเจ็กต์ให้กลายเป็นออบเจ็กต์เดียว

const errObj = Object.assign(...err);

ขั้นตอน 2 − ลบคุณสมบัติ chk

delete errObj['chk']; console.log(errObj);

โค้ดเต็มพร้อม Output ด้านล่าง

ตัวอย่าง

const err = [    {       "chk" : true,       "name": "test"    },    {       "chk" :true,       "post": "test"    } ]; const errObj = Object.assign(...err); delete errObj['chk']; console.log(errObj);

ผลลัพธ์

ผลลัพธ์ใน Console จะเป็น −

{ name: 'test', post: 'test' }