0

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

asked Nov 6, 2019 at 23:07
4
  • What you tried? Commented Nov 6, 2019 at 23:10
  • Use split() to split the strings into arrays. Then loop over them and create an array of objects. Commented Nov 6, 2019 at 23:10
  • 2
    Why does pdate have a delimiter at the beginning, but the other strings don't? Commented Nov 6, 2019 at 23:11
  • 3
    That's not a multidimensional array. It's a 1-dimensional array of objects. Commented Nov 6, 2019 at 23:11

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I think getData(c) is only redundant split wrapper leading for larger complexity IMO
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.