我有一个对象
cart {
KDR010011: {
barcode: "0"
brand: "Kapal Api"
category: "KEBUTUHAN DAPUR"
cost_price: "107569.66490299824"
cost_price_per_piece: 896.413874191652
name: "Kapal Api 25g sp mix"
product_id: "KDR010011"
qty: 1
qty_per_box: 120
selling_price: 116000
selling_price_per_piece: 962.5
},
KDR010125: {
barcode: ""
brand: "Kapal Api"
category: "KEBUTUHAN DAPUR"
cost_price: "110317.63859070961"
cost_price_per_piece: 835.7396862932546
name: "ABC Susu 31g"
product_id: "KDR010125"
qty: 5
qty_per_box: 132
selling_price: 113000
selling_price_per_piece: 863.6363636363636
}
}
我想删除该属性,结果是我想要的:
cart {
KDR010011: {
qty: 1
selling_price: 116000
},
KDR010125: {
qty: 5
selling_price: 113000
}
}
我正在使用underscore js library,结果是这样的:
我该怎么办?
答案 0 :(得分:1)
您可以通过在对象的键上循环并将每个键的值分配回原始对象来轻松实现此目的。如果您不想修改原始对象,只需将键分配给新对象。
我个人将更改数据结构,以使购物车是一个对象数组,每个对象都将KDR010011
键作为属性。
const obj = {
KDR010011: {
barcode: "0",
brand: "Kapal Api",
category: "KEBUTUHAN DAPUR",
cost_price: "107569.66490299824",
cost_price_per_piece: 896.413874191652,
name: "Kapal Api 25g sp mix",
product_id: "KDR010011",
qty: 1,
qty_per_box: 120,
selling_price: 116000,
selling_price_per_piece: 962.5,
},
KDR010125: {
barcode: "",
brand: "Kapal Api",
category: "KEBUTUHAN DAPUR",
cost_price: "110317.63859070961",
cost_price_per_piece: 835.7396862932546,
name: "ABC Susu 31g",
product_id: "KDR010125",
qty: 5,
qty_per_box: 132,
selling_price: 113000,
selling_price_per_piece: 863.6363636363636,
}
}
Object.keys(obj).forEach(key => obj[key] = {
qty: obj[key].qty,
selling_price: obj[key].selling_price,
})
console.log(obj)
答案 1 :(得分:0)
您可以尝试以下方法:
const newCart = {...cart}
Object.keys(newCart).forEach(key => {
newCart[key] = {
qty: newCart[key].qti,
selling_price: newCart[key].sailing_price
}
}
答案 2 :(得分:-1)
您的对象中需要逗号
我觉得我可以比这里更好地使用解构
const cart = {
KDR010011: {
barcode: "0",
brand: "Kapal Api",
category: "KEBUTUHAN DAPUR",
cost_price: "107569.66490299824",
cost_price_per_piece: 896.413874191652,
name: "Kapal Api 25g sp mix",
product_id: "KDR010011",
qty: 1,
qty_per_box: 120,
selling_price: 116000,
selling_price_per_piece: 962.5
},
KDR010125: {
barcode: "",
brand: "Kapal Api",
category: "KEBUTUHAN DAPUR",
cost_price: "110317.63859070961",
cost_price_per_piece: 835.7396862932546,
name: "ABC Susu 31g",
product_id: "KDR010125",
qty: 5,
qty_per_box: 132,
selling_price: 113000,
selling_price_per_piece: 863.6363636363636
}
}
let newCart = {}
Object.keys(cart).forEach(key => newCart[key] = { qty: cart[key].qty, selling_price : cart[key].selling_price })
console.log(newCart)