Home > Net >  How to duplicate data with the same name?
How to duplicate data with the same name?

Time:03-19

My code:

this.temp1.push(this.json);

for(let i=0; i<this.temp1.length; i  ){
    if(this.temp1[i].name == this.json.name){       
        this.orderList[i] = this.json;
        this.DBorder[i] = this.order_json;      
    }
    else{
        this.orderList.push(this.json);
        this.DBorder.push(this.order_json);
    }
}

My first input data:

[{"name":"Pad-Thai", "price":10,"amount":1,"total":10}]

My second input data (with a new amount):

[{"name":"Pad-Thai", "price":10,"amount":3,"total":30}]

Current result:

[{"name":"Pad-Thai", "price":10,"amount":3,"total":30},
{"name":"Pad-Thai", "price":10,"amount":3,"total":30}]

Expected result:

[{"name":"Pad-Thai", "price":10,"amount":3,"total":30}]

CodePudding user response:

  1. Check name and update if exist else inset while adding new object in array.

        const obj1 = { "name": "Pad-Thai", "price": 10, "amount": 1, "total": 10 };
            const obj2 = { "name": "Pad-Thai", "price": 10, "amount": 3, "total": 30 };
            const obj3 = { "name": "Some-Other-Dish", "price": 20, "amount": 2, "total": 40 };
    
            let temp1 = [];
            function addItem(obj) {
                let index = temp1.findIndex(x => x.name === obj.name);
                if (index > -1) {
                    temp1[index] = obj;
                } else {
                    temp1.push(obj);
                }
            }
            addItem(obj1);
            addItem(obj2);
            addItem(obj3);
            console.log('temp1 : ', temp1);

  2. If you have already added obj with same name then you can remove using for loop and find index or reduce loop

        const output = [
            { "name": "Pad-Thai", "price": 10, "amount": 1, "total": 10 },
            { "name": "Pad-Thai", "price": 10, "amount": 3, "total": 30 },
            { "name": "Some-Other-Dish", "price": 20, "amount": 2, "total": 40 }
        ]
    
        let temp1 = [];
        output.forEach(obj => {
            let index = temp1.findIndex(x => x.name === obj.name);
            if (index > -1) {
                temp1[index] = obj;
            } else {
                temp1.push(obj);
            } 
        });
        console.log('temp1 : ', temp1);

CodePudding user response:

const input1 = [{
  "name": "Pad-Thai",
  "price": 10,
  "amount": 3,
  "total": 10
}]
const input2 = [{
  "name": "Pad-Thai",
  "price": 10,
  "amount": 3,
  "total": 30
}];

function merge(existing, update, identifier) {
  const mapped = update.reduce((acc, el) => {
    return { ...acc,
      [el[identifier]]: el
    };
  }, {});

  return existing.map(el => {
    const altered = { ...el,
      ...mapped[el[identifier]]
    };
    
    delete mapped[el[identifier]];

    return altered;
  }).concat(Object.values(mapped));
}

console.log(merge(input1, input2, "name"));

  • Related