Home > Net >  populate object with new object in javascript
populate object with new object in javascript

Time:10-12

how do I combine two objects so that it looks like the following code

{
  category: 'product 1',
  sub_category: 'sub product 1',
}
{
  nama: "nama product1",
  jenis: "jenis1"
}

{
  nama: "nama product1",
  jenis: "jenis1",
  category: {
    category: 'product 1',
    sub_category: 'sub product 1',
  }
}

Please help me

CodePudding user response:

Use spread

const x = {
  category: 'product 1',
  sub_category: 'sub product 1',
}
const y = {
  nama: "nama product1",
  jenis: "jenis1"
};

const z = {...y, category: x};

const log = document.querySelector(`pre`);

log.textContent = `nested:\n`   JSON.stringify(z, null, 2);

// or flattened:
const zz = { ...y, ...{ category: x.category, sub_category: x.sub_category } };
log.textContent  = `\n\nflat:\n${JSON.stringify(zz, null, 2)}`;
<pre></pre>

CodePudding user response:

You could do something simple like this, assuming that all objects have the same format

const obj1 = {
    category: 'product 1',
    sub_category: 'sub product 1',
}
const obj2 = {
    nama: "nama product1",
    jenis: "jenis1"
}

obj2.category = obj1;
console.log(obj2);

  • Related