Home > database >  insert multiple object with same key-value in array based on condition in javascript
insert multiple object with same key-value in array based on condition in javascript

Time:04-09

I have object that has multiple values for example

let obj = {
  a: "day1",
  b: "",
  c: "day3",
  aa: 10,
  bb: 11,
  cc: 12,
}
let data = {};
let item = [];
for (let i in obj) {
  if (i === 'a') {
    data["title"] = obj.a;
    data['value'] = obj.aa;
  }
  if (i === 'b') {
    data["title"] = obj.b;
    data['value'] = obj.bb;
  }
  if (i === 'c') {
    data["title"] = obj.c;
    data['value'] = obj.cc;
  }
  item.push(data);
}
console.log(item)

but I'm getting only last day3 value in multiple times .

item [
        {title:"day3",value:12},
        {title:"day3",value:12},
{title:"day3",value:11}
        ]

I want in the following format

item [
    {title:"day1",value:10},
    {title:"day3",value:11}
    ]

please help, thanks in advance.

CodePudding user response:

You should declare the data variable inside the loop because otherwise you are always changing its value at each iteration and that object is what you are adding to the item variable and its value it's always written over the previous one. If you create a new object at each iteration it will be on its own and no further iteration is going to overwrite its value.

*As it was pointed out in the comments, I added a check in your loop to skip iterations not belonging to the cases: 'a','b','c'; so that your final array won't contain empty objects.

let obj = {
  a: "day1",
  b: "",
  c: "day3",
  aa: 10,
  bb: 11,
  cc: 12,
}
let item = [];
for (let i in obj) {

  //this check decides if you want to skip this iteration
  //so that you won't have empty object appended to your result array
  //if(i!='a' && i!='b' && i!='c')
  //    continue;
  //this check was replaced by the final check later for better mantainance
  
  //this was (before) the only thing I changed
  let data = {};
  if (i === 'a') {
    data["title"] = obj.a;
    data['value'] = obj.aa;
  }
  if (i === 'b') {
    data["title"] = obj.b;
    data['value'] = obj.bb;
  }
  if (i === 'c') {
    data["title"] = obj.c;
    data['value'] = obj.cc;
  }

  let isEmpty = Object.keys(data).length === 0;
  //this will check if data is empty before pushing it to the array
  if(!isEmpty)
      item.push(data);
}
console.log(item)

CodePudding user response:

From the above comments ...

"Of cause the OP gets the last state since the OP always reassigns the same properties (title and value) at one and the same data object. The OP wants to use an array and push at/each time a newly created data object into it."

Peter Seliger can you give me any example of solution – omkar p

const obj = {
  a: "day1",
  b: "",
  c: "day3",
  aa: 10,
  bb: 11,
  cc: 12,
}
const items = [];

// slightly fixed OP approach.
for (const key in obj) {
  if (key === 'a') {
    items.push({
      title: obj.a,
      value: obj.aa,
    });
  }
  if (key === 'b') {
    items.push({
      title: obj.b,
      value: obj.bb,
    });
  }
  if (key === 'c') {
    items.push({
      title: obj.c,
      value: obj.cc,
    });
  }
}
console.log({ items });

// or entirely generic/configurable and maybe even more expressive ...
console.log(
  Object
    .entries(obj)
    .reduce(({ target, valueMap, result }, [key, value]) => {

      if (key in valueMap) {
        result.push({
          title: value,
          value: target[valueMap[key]],
        });
      }
      return { target, valueMap, result };
    }, {
      target: obj,
      valueMap: { a: 'aa', b: 'bb', c: 'cc' },
      result: [],

    }).result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related