应该是神速的快速解决方案(不幸的是,我不是那样!)我正在努力处理一些json(在代码下面)。我正在尝试创建一个名为“ dollar_price”的新键值对。这可以通过将“ price”和“ index_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
}
你为什么不这样做
dp.dollar_price = result.map(({price, index_price}) => price * index_price)[0];
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 );