Javascript 如何避免嵌套映射以从嵌套数组获取所需的值?
我正在这样做,以获得我需要的值:Javascript 如何避免嵌套映射以从嵌套数组获取所需的值?,javascript,arrays,ecmascript-6,lodash,Javascript,Arrays,Ecmascript 6,Lodash,我正在这样做,以获得我需要的值: tableRowsItems = data.softy.map(row => row.items.map(item => console.log('item', item)), ); 有了这些,我得到了下面图片中的东西,这正是我所需要的 我的问题是,这是否是正确的ES6方法。 如果有帮助的话,我也在使用lodash 这是json文件在没有映射的情况下的外观: [ { "ticketId": 67973802,
tableRowsItems = data.softy.map(row =>
row.items.map(item => console.log('item', item)),
);
有了这些,我得到了下面图片中的东西,这正是我所需要的
我的问题是,这是否是正确的ES6方法。
如果有帮助的话,我也在使用lodash
这是json文件在没有映射的情况下的外观:
[
{
"ticketId": 67973802,
"account": null,
"items": [
{
"id": 11705294,
"billingItemId": 361643044,
"cancellationRequestId": 17289674,
"immediateCancellationFlag": true,
"scheduledCancellationDate": null,
"serviceReclaimStatusCode": "COMPLETE",
"billingItem": {
"description": "Storage as a Service",
"recurringFee": 0,
"id": 361643044
}
}
]
},
...
]
...
我需要的是您在
项
键上看到的内容如果我正确理解您的问题,您将尝试从票证
对象数组中提取所有嵌套的项
,在这种情况下,您可以通过将输入票证映射到项
数组来实现这一点,然后将结果展平,将其压缩成一个平面,一组item
对象如下:
var output = input
.map(ticket => ticket.items) // Map each ticket to array of ticket items
.flat(); // Reduce array of item arrays to combined array of items
var输入=[
{
“ticketId”:67973802,
“帐户”:空,
“项目”:[
{
“id”:11705294,
“billingItemId”:361643044,
“cancellationRequestId”:17289674,
“立即取消”标志:正确,
“scheduledCancellationDate”:空,
“服务回收状态代码”:“完成”,
“账单项目”:{
“说明”:“存储即服务”,
“复发费”:0,
“id”:361643044
}
}
]
},
{
“ticketId”:67973802,
“帐户”:空,
“项目”:[
{
“id”:11705294,
“billingItemId”:361643044,
“cancellationRequestId”:17289674,
“立即取消”标志:正确,
“scheduledCancellationDate”:空,
“服务回收状态代码”:“完成”,
“账单项目”:{
“说明”:“存储即服务”,
“复发费”:0,
“id”:361643044
}
}
]
}
];
var output=input.map(ticket=>ticket.items.flat();
控制台日志(输出)代码>Lodash已经提供了(JS版本尚未在所有浏览器上支持),您可以将其用作:
var items = _.flatMap(tickets, t => t.items);
要从单个一维数组中的所有票据中获取所有项目
:
var票据=[{
“ticketId”:67973802,
“帐户”:空,
“项目”:[{
“id”:117052912,
“billingItemId”:36164304123,
}, {
“id”:11705232,
“billingItemId”:361643044,
}]
},
{
“ticketId”:67973802,
“帐户”:空,
“项目”:[{
“id”:117052945,
“billingItemId”:361643046,
}, {
“id”:117052953,
“billingItemId”:361643049,
}]
}
];
var items=uu.flatMap(tickets,t=>t.items);
控制台日志(项目)代码>
使用ES6您可以通过以下方式轻松执行单行函数,通过项
属性帮助您展平嵌套数组:
var tickets=[{“ticketId”:67973802,“account”:null,“items”:[{“id”:117052912,“billingItemId”:36164304123,},{“id”:11705232,“billingItemId”:361643044,}],{“ticketId”:67973802,“account”:null,“items”:[{“id”:117052945,“billingItemId”:361643046,},{“id”:117052953,“billingItemId”:361643049,}];
常量pullBy=(arr,prop)=>arr.reduce((r,c)=>[…r[prop],…c[prop])
console.log(pullBy(tickets,'items'))
以上答案将帮助您实现目标,但当我们希望从循环返回某些内容时,我们使用.map
,否则您应该使用forEach
我知道给出的问题实际上是无关紧要的,但仍然如此。想把它放到线程中。所以你想把每个票证中的所有项目
放到一个数组中?这不是正确的方法,因为你没有返回任何有意义的。map
-改用forEach
,对于泛型迭代+副作用,需要注意的是,这是一个实验特性,目前还不太受支持。如果要在web浏览器中运行,您可能需要。