2

I would like to know how to create new object by two objects in javascript.

iterate through the obj1, and add the obj2 values, create new object in javascript

function getObject(obj1, obj2){
  let result={};
  Object.keys(obj1).forEach(key=>{
    if(key==="start" || key==="end"){
      result.time= obj1.start+"-"+obj1.end,
      result.qty= obj2.qty
    }
  }) 

}

var obj1 ={
  start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

var obj2 = {
  qty: 10, 
  amt: 120
}

Expected Output

 {
   time: "16:01-23:59"
   val: 10 // represents obj2.qty,
   totalqty: 1065, 
   totalamount: 8229170,
   price: 120
 }

ved
  • 167
  • 9

2 Answers2

1

You can write a function and get desired properties:

var obj1 ={
  start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

var obj2 = {
  qty: 10,
  amt: 120
}

const merge = (obj1, obj2) => {
  return {
    time: obj1.start + '-' + obj1.end,
    val: obj2.qty,
    totalqty: obj1.totalqty,
    totalamount: obj1.totalamount,
    price: obj2.amt
  };
}

console.log(merge(obj1, obj2));

In addition, you can use spread syntax, but it merges all properties:

let obj1 ={
  start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

let obj2 = {
  qty: 10, 
  amt: 120
}

let merged = {...obj1, ...obj2};
console.log(merged );

or try to use Object.assign() and it is also merges all properties:

var obj1 ={
  start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

var obj2 = {
  qty: 10, 
  amt: 120
}

var result = Object.assign({}, obj1, obj2);
console.log(result);

Read more Object.assign() here.

StepUp
  • 36,391
  • 15
  • 88
  • 148
1

You could destructure the objects, rename some properties and return a new object.

const
    merge = ({ start, end, totalqty, totalamount }, { qty: val, amt: price }) =>
        ({ time: start + "-" + end, val, totalqty, totalamount, price}),
    obj1 = { start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170 },
    obj2 = { qty: 10, amt: 120 };

console.log(merge(obj1, obj2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392