How do i create a multi-dimensional array from different javascript variables ?
For example, i have these three variables
var pdate = "|2019年12月26日|2019年12月26日|2019年12月26日"
var products_id = "3354|5009|61927"
var products_category = "ENERGETICS|CASIO|SEIKO"
And i would like to transform them into this
var products_list = []
[0] = {pdate:"2019-12-26",products_id:"3354",products_category:"ENERGETICS"}
[1] = {pdate":"2019-12-26",products_id:"5009",products_category:"CASIO"}
[2] = {pdate:"2019-12-26",products_id:"61927",products_category:"SEIKO"}
Any ideas ?
Thanks
2 Answers 2
You can use the function split to separate the datas:
var pdate = "2019-12-26|2019年12月26日|2019年12月26日";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
var arrayPdate = getData(pdate);
var arrayProducts_id = getData(products_id);
var arrayProducts_category = getData(products_category);
var result = []
for (let i = 0; i < arrayPdate.length; i++) {
let jsonObject = {
pdate: arrayPdate[i],
products_id: arrayProducts_id[i],
products_category: arrayProducts_category[i]
}
result.push(jsonObject)
}
console.log(result);
function getData(c) {
return c.split("|")
}
answered Nov 6, 2019 at 23:23
user7396942
Sign up to request clarification or add additional context in comments.
1 Comment
daremachine
I think getData(c) is only redundant split wrapper leading for larger complexity IMO
You need use .split function on your string and then use loop with array index for others.
var pdate = "2019-12-26|2019年12月26日|2019年12月26日";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
pdate = pdate.split('|');
products_id = products_id.split('|');
products_category = products_category.split('|');
let arr = [];
for(let i=0; i<pdate.length; i++) {
arr.push({
pdate: pdate[i],
products_id: products_id[i],
products_category: products_category[i]
});
}
console.log(arr);
answered Nov 6, 2019 at 23:16
daremachine
2,7982 gold badges27 silver badges36 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js
split()to split the strings into arrays. Then loop over them and create an array of objects.pdatehave a delimiter at the beginning, but the other strings don't?