我有一个具有多个值的对象,例如
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)
但我只能多次得到最后一个day3值。
item [
{title:"day3",value:12},
{title:"day3",value:12},
{title:"day3",value:11}
]我想要下列格式
item [
{title:"day1",value:10},
{title:"day3",value:11}
]请帮忙,谢谢。
发布于 2022-04-08 11:36:17
您应该在循环中声明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)
发布于 2022-04-08 11:40:13
从上面的评论..。
当然,OP获得了最后一个状态,因为OP总是在一个和相同的
对象上重新分配相同的属性(__、
title和value__)。OP希望使用数组,每次新创建的data对象都按/推。
你能给我一个解决方案的例子吗??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; }
发布于 2022-06-11 03:57:55
数组加载对象需要深拷贝,
// 多个对象载入 数组中,需要深拷贝,不然键指相同
let objXXX = {
a:123,
b:456,
C:789
};
let arrYYY = [];
arrYYY[0] = JSON.parse(JSON.stringify(objXXX));
arrYYY[1] = JSON.parse(JSON.stringify(objXXX));
arrYYY[0].a = "123";
arrYYY[1].a = "9923";
// 0: Object { a: "123", b: 456, C: 789 }
// 1: Object { a: "9923", b: 456, C: 789 }
console.log(arrYYY);https://stackoverflow.com/questions/71796126
复制相似问题