在本机中循环数组

问题描述 投票:0回答:1

enter image description here这些是我的输入数组(service_item_list)...

for (var k = 0; k < service_item_list.length; k++) {
            for (var l = 0; l < service_item_list[k].length; l++) {
                service_item_list[k][l].service_id=this.state.selected_services[k].id
            }
        }



service_item_list=[[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}],[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}]]

this.state.selected_services=[{id:'5',event_id:'1'},{id:'6',event_id:'1'}]

...我不断得到输出:...

service_item_list=[[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}],[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}]]

...但我需要输出:...

 service_item_list=[[{event_id:'1',service_id:'5',product_id:''},{event_id:'1',service_id:'5',product_id:''},{event_id:'1',service_id:'5',product_id:''}],[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}]]

...我找不到错误在哪里???

arrays react-native for-loop multidimensional-array iteration
1个回答
0
投票

您可以使用JavaScript数组映射方法简化事情。因此,方法将如下所示:

const service_item_list=[[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}],[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}]]

const selected_services=[{id:'5',event_id:'1'},{id:'6',event_id:'1'}]

const res = service_item_list.map((arr, outerIdx) => {
    return arr.map((obj) => {
        obj.service_id = selected_services[outerIdx].id
        return obj;
    })
})

console.log(res)

[
    [
        { event_id: '', service_id: '5', product_id: '' },
        { event_id: '', service_id: '5', product_id: '' },
        { event_id: '', service_id: '5', product_id: '' },
    ],
    [
        { event_id: '', service_id: '6', product_id: '' },
        { event_id: '', service_id: '6', product_id: '' },
        { event_id: '', service_id: '6', product_id: '' },
    ],
];

存储在res常量中的值将是您的结果,如上所示。有关JS数组映射方法here的更多信息>

© www.soinside.com 2019 - 2024. All rights reserved.