根据 javascript 中的条件在数组中插入具有相同键值的多个对象

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

我的对象有多个值,例如

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)

但我多次只得到最后一天 3 的值。

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

我想要以下格式

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

请帮忙,提前致谢。

您应该在循环内声明 data 变量,否则您总是在每次迭代时更改它的值,并且该对象就是您要添加到 item 变量的对象,它的值总是写在前一个上。如果您在每次迭代中创建一个新对象,它将独立存在,并且没有进一步的迭代将覆盖它的值。

*正如评论中指出的那样,我在您的循环中添加了一个检查以跳过不属于以下情况的迭代:'a'、'b'、'c';这样你的最终数组就不会包含空对象。

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)

从以上评论...

"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; }