我正在将对象保存在以下状态:
ingredients: {
salad: {
amount: 3,
basePrice: 1
},
cheese: {
amount: 2,
basePrice: 1.2
}
}
我想在我的组件状态中使用它,如下所示
ingredients: {
salad: 3,
cheese: 2
}
我最初使用Object.keys
和map
,但它返回一个键值对的数组,而不是对象。
虽然这有效:
const newIngredientsObject = {};
for (const i in ingredientsObject)
newIngredientsObject[i] = ingredientsObject[i].amount;
return newIngredientsObject;
我想找到一个没有辅助方法的解决方案,如下:
const mapStateToProps = state => {
return {
ingredients: Object.keys(state.burger.ingredients).map(i => (
{ [i]: state.burger.ingredients[i].amount } )),
totalPrice: state.burger.totalPrice
}
};
答案 0 :(得分:0)
您可以使用值的amount
属性映射对象的条目,并使用Object.assign
获取新对象。
var ingredients = { salad: { amount: 3, basePrice: 1 }, cheese: { amount: 2, basePrice: 1.2 } },
result = Object.assign(
...Object.entries(ingredients).map(([key, value]) => ({ [key]: value.amount }))
);
console.log(result);
答案 1 :(得分:0)
当你想在另一个对象中创建一个对象时,请访问此网站
object 1 = {
content 1 = {
stuff = {
},
more Stuff = {
}
}
} 对象2 = { 关键1:“”, 关键2:“”
} object 1.content 1 = object 2;
答案 2 :(得分:0)
你问了一个使用Object.keys的解决方案,这里有一个:
var x = {ingredients: {
salad: {
amount: 3,
basePrice: 1
},
cheese: {
amount: 2,
basePrice: 1.2
}
}}
Object.keys(x.ingredients).map((d,i)=>[d,x.ingredients[d].amount]).reduce((ac,d,i)=>(ac[d[0]]=d[1],ac),{})
//{salad: 3, cheese: 2}
答案 3 :(得分:0)
最短的我可以使用Object.keys
和reduce
const ingredients = {
salad: {
amount: 3,
basePrice: 1
},
cheese: {
amount: 2,
basePrice: 1.2
}
};
let newObject = Object.keys(ingredients).reduce((acc, val) => {
acc[val] = ingredients[val].amount;
return acc;
}, {});
console.log(newObject);

答案 4 :(得分:0)
<强> ANSWER 强>: 感谢@ibowankenobi和@Nina Scholz
提供的解决方案
Object.keys(ingredients)
.map( (d, i) => [d, ingredients[d].amount])
.reduce( (ac, d, i) => (ac[d[0]] = d[1], ac), {} );
Object.assign(...Object.entries(ingredients)
.map( ([key, value]) => ({ [key]: value.amount }) ) );
reduce: 0.0849609375ms
entries: 0.1650390625ms
forLoop: 0.07421875ms
reduce: 0.024169921875ms
entries: 0.048095703125ms
forLoop: 0.010009765625ms
reduce: 0.010009765625ms
entries: 0.016845703125ms
forLoop: 0.0078125ms
经过一些测试后,似乎使用for循环是最有效的,之后是reduce函数。