javascript - Object.Assign 以数组形式返回值,要求以对象形式返回
问题描述
应该是一个高手的快速解决方案(遗憾的是我不是那样!)我正在努力处理一些 json 的操作(下面的代码)。我正在尝试创建一个名为“dollar_price”的新键值对。这将通过将“价格”和“索引价格”值相乘来实现。我能够进行乘法并将新创建的键和值插入到 json 中,但由于某种原因,它将值作为自己的数组插入。
var result = result.map(function(el) {
var dp = Object.assign({}, el);
//I tried the line below as well but no luck :(
//var dp = Object.assign.apply(Object, [{}].concat(el));
dp.dollar_price = result.map(({price, index_price}) => price * index_price);
return dp;
});
JSON当前输出:
{ price: 5,
index_price: 20,
dollar_price: [100],
key3: value3
}
预期的输出应该是:
{ price: 5,
index_price: 20,
dollar_price: 100,
key3: value3
}
解决方案
const data = [{
price: 5,
index_price: 20,
key3: 1
}]
var result = data.map(pr => ({...pr, dollar_price: pr.price * pr.index_price}));
console.log(result );
推荐阅读
- java - 如何在java中使用switch语句和数组?
- java - Java Regex:查找带转义的单引号文本
- probability - h2o decision tree leaf value interpretation
- python - Create a text file to save data from each scraped URL
- c# - How to scroll a invisible element in the picker using xamarin ui test?
- ruby-on-rails - 如何修复“未定义的方法‘用户’(ActiveRecord_Associations_CollectionProxy)
- search - How to get Parent Document of matching Child Document in Query?
- scala - spark中的rdd.collect().map,编译需要时间
- rust - 如何正确重新分配选项数组中的值?
- python - 在基于 Django 类的视图中传递查询参数