【问题标题】:Object.Assign returns value as an array, require as an objectObject.Assign 以数组形式返回值,要求以对象形式返回
【发布时间】:2020-09-27 15:32:38
【问题描述】:

应该是一个高手的快速解决方案(遗憾的是,我不是那样!)我正在努力处理一些 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
}

【问题讨论】:

    标签: javascript node.js arrays json object


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你为什么不这样做

      dp.dollar_price = result.map(({price, index_price}) => price * index_price)[0];
      

      【讨论】:

        【解决方案3】:

        你可以试试这个

              f=(_)=>({..._,dollar_price:_.price*_.index_price})
              console.log(data.map(f))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-03
          • 2017-04-04
          • 1970-01-01
          • 2018-01-11
          • 1970-01-01
          • 2010-10-09
          • 2012-05-19
          • 1970-01-01
          相关资源
          最近更新 更多