首页 > 解决方案 > 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
}

标签: javascriptnode.jsarraysjsonobject

解决方案


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 );


推荐阅读