如何使用lodash

时间:2018-08-22 12:59:12

标签: javascript lodash

我目前有这个对象数组:

[{
   "key1": "value1",
   "key2": "value2",
   "key3": "valuex"
},{
   "key1": "value3",
   "key2": "value4",
   "key3": "valuey"
}]

我最后想要得到的是一个字符串数组

["value1/value2", "value3/value4"]

最好使用一些“ lodash魔术快捷方式”。

从本质上讲,我想将key1和key2的值连接到使用'/'作为分隔符的字符串,而忽略key3。

我使用_.transform_.join进行了很多尝试,但是我的尝试都没有达到预期的结果。我知道这不是免费的编码服务,但是也许您对我有提示?

3 个答案:

答案 0 :(得分:3)

使用lodash.map

var data = [{
  "key1": "value1",
  "key2": "value2",
  "key3": "valuex"
}, {
  "key1": "value3",
  "key2": "value4",
  "key3": "valuey"
}]

console.log(_.map(data, ob => `${ob.key2}/${ob.key2}`));
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>

答案 1 :(得分:2)

不使用lodash,但同样神奇(纯香草js)

let response = [{
       "key1": "value1",
       "key2": "value2",
       "key3": "valuex"
    },{
       "key1": "value3",
       "key2": "value4",
       "key3": "valuey"
    }].map(el => `${el.key1}/${el.key2}`);
    
   console.log(response);

答案 2 :(得分:1)

这不是使用Lodash,而是:

const myArray = [{
   "key1": "value1",
   "key2": "value2",
   "key3": "valuex"
},{
   "key1": "value3",
   "key2": "value4",
   "key3": "valuey"
}]

const newArray = myArray.map(element => element.key1 + '/' + element.key2)

console.log(newArray)