如何使用Lodash在地图中制作2个元素

时间:2017-02-11 11:12:56

标签: javascript arrays dictionary lodash

我有一系列对象说:

let array = [{x: 3}, {x: 4}, {x: 5}];

我想映射它并在每个现有元素之后添加新元素。所以为了保持简单,我想得到:

let mappedArray = [{x: 3}, {y: 3}, {x: 4}, {y: 4}, {x: 5}, {y: 5}];

可以像这样扁平化来完成:

let mappedAray = _(array)
    .map(obj => {return [obj, {y: obj.x}]})
    .flatten()
    .value();

但我想知道可能有更优雅的解决方案。我不知道的某种oneliner方法。

3 个答案:

答案 0 :(得分:2)

您可以在普通javascript中使用reduce()



let array = [{x: 3}, {x: 4}, {x: 5}];
var result = array.reduce((r, e) => (r.push(e, {y: e.x}), r), [])

console.log(result)




答案 1 :(得分:0)

使用Array.prototype.forEach()Array.prototype.push()函数的解决方案:



var arr = [{x: 3}, {x: 4}, {x: 5}], result = [];

arr.forEach(function(o){ result.push(o, {y: o.x}) });    
console.log(result);




答案 2 :(得分:0)

你不能只使用Object.assign吗?



import random

def guessnum():
  randomnum = random.randint(1,6)
  awnser = input ("what do you think the number is? ")
  if awnser==randomnum:
    print ("good job. you are correct. ")
  else:
    print ("incorrect. better luck next time. ")

restart = input ("would you like to try again? ")
if restart == "Yes" or "y":
  guessnum()
else:
  end()