[英]Lodash find object in nexted array
I am currently working on an assignment in which I have to use Lodash
and find an object inside JSON array. 我目前正在处理一个作业,其中必须使用
Lodash
并在JSON数组中找到一个对象。 Below is my JSON
string 以下是我的
JSON
字符串
var options = {
'axisSeries': [
["xText", "xValue"],
["yText", "yValue"]
]
}
Now using Lodash
I want to find string in 2nd Index of each array of axisSeries
. 现在使用
Lodash
我想在axisSeries
的每个数组的2nd Index中找到字符串。
So for example if I search xValue
. 例如,如果我搜索
xValue
。 it should return me object as it is available in 2nd Index of First Array. 它应该返回我对象,因为它在第一个数组的第二个索引中可用。 Same for
yValue
. 与
yValue
相同。
But it should not return object for xText
and yText
as both of them are not available in second index. 但是它不应返回
xText
和yText
对象,因为它们在第二个索引中均不可用。
to do so I want to use Lodash
for that. 为此,我想使用
Lodash
。 But I could not find any appropriate function for this. 但是我找不到适合的功能。
I think your JSON should be like, 我认为您的JSON应该像
var options = {
'axisSeries': [
{ 'xText': 'X Text', 'xValue': 10 },
{ 'yText': 'Y Text', 'yValue': 20 }
]
}
And in Lodash use _.pluck() to get xValue
like, 在Lodash中使用_.pluck()获得
xValue
,
_.pluck(options.axisSeries, 'xValue');
// should return [10]
Alternatively, You can use _.map() , 或者,您可以使用_.map() ,
_.map(options.axisSeries, 'xValue');
If you want to get the whole array by xValue
then you can use _.filter() like, 如果您想通过
xValue
获取整个数组,则可以使用_.filter() ,
var options = { 'axisSeries': [ ["xText", "xValue"], ["yText", "yValue"] ] } console.log( _.filter(options.axisSeries, function(o) { return o.indexOf('xValue')!=-1; }) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You could use _.map
with _.last
, or if you need to get a specific index you could use _.nth
. 您可以将
_.map
与_.last
_.map
使用,或者如果需要获取特定的索引,则可以使用_.nth
。 Also you should tell your teacher about ramda . 您还应该向您的老师介绍ramda 。 it has a better structure and capability to compose functions.
它具有更好的结构和功能组合功能。
var options = { 'axisSeries': [ ["xText", "xValue"], ["yText", "yValue"] ] } console.log( _.map(options.axisSeries, _.last), _.map(options.axisSeries, xs => _.nth(xs, 1)) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.