hi can you help me for looping and add array multidimential, because in php it's like easy for create array multi dimention but in javascript i don't know how to make array multidimential but i try like this but error and i don't have any idea
data_array.forEach((element,i) => {
data1[element.produsen_id][element.category_id] = element.data_value
})
i try explain for the excel data
this json format what i need
{"main_report": {
"value": {
"2": {
"5": "0",
"7": "0",
"3": "13",
"1": "3",
"10": "0",
"9": "4",
"2": "3",
"8": "0"
},
"3": {
"2": "3",
"10": "0",
"1": "2",
"5": "0",
"3": "0",
"9": "0",
"8": "7"
},
"4": {
"3": "2",
"10": "0",
"1": "2",
"8": "3",
"2": "2",
"5": "0",
"9": "4",
"7": "1"
},
"5": {
"5": "0",
"10": "0"
},
"7": {
"3": "0"
},
"8": {
"1": "4",
"7": "0",
"8": "0"
},
"9": {
"9": "0",
"1": "0",
"3": "0",
"7": "1",
"5": "0"
},
"10": {
"3": "0"
},
"11": {
"7": "0",
"2": "1",
"3": "11",
"9": "3",
"8": "0",
"1": "1"
},
"13": {
"5": "0",
"2": "0",
"8": "0",
"10": "5",
"3": "1",
"1": "0",
"9": "0"
},
"15": {
"10": "0"
},
"16": {
"10": "0"
},
"17": {
"10": "0"
},
"18": {
"10": "0"
},
"19": {
"10": "0"
},
"1": {
"2": "4",
"9": "9",
"3": "8",
"7": "5",
"1": "6",
"4": "2",
"5": "2"
},
"6": {
"7": "0",
"3": "3",
"2": "1",
"9": "1",
"1": "1"
},
"20": {
"1": "4",
"2": "3",
"9": "5",
"3": "13",
"4": "0",
"7": "1",
"10": "0"
}
}
} }
in php looping like this
foreach($result as $key=>$value){
$return_arr[$value->id_1][$value->id2] = $value->value_data;
}
how to implement in javascript, i will appriciate for your answer thankyou
CodePudding user response:
Solutions:
We are gonna use objects instead of arrays.
Initialize data1 with empty object data1 = {}
and now:
Solution 1:
data_array.forEach((element) => {
// if data1[element.produsen_id] doesn't exist yet
if(!data1[element.produsen_id]) {
data1[element.produsen_id] = {}
}
data1[element.produsen_id][element.category_id] = element.data_value
})
Solution 2 (alternatively):
data_array.forEach((element,i) => {
data1[element.produsen_id] = {
...(data1[element.produsen_id] || {}),
[element.category_id]: element.data_value
}
})
CodePudding user response:
These are nested objects you have not multidimensional arrays {} are for objects and [] are for arrays
CodePudding user response:
What kind of error do you get? Maybe this is the solution
data_array.forEach((element) => {
// if data1[element.produsen_id] doesn't exist yet
if(!data1[element.produsen_id]) {
data1[element.produsen_id] = []
}
data1[element.produsen_id][element.category_id] = element.data_value
})