0

I am trying to take a JSON array like this

[Alex, James, John]

and create seperate JSON arrays for them like this

[[Alex], [James], [John]]

So I can then insert the JSON payload into a datatable using Datatables.JS

So far I have this

var data = json;
while (data.length) {
  console.log(data.splice(0, 1));
}
return data;

Now this splits the JSON into 3 seperate arrays but when I try to use the data variable in the datatables.JS, it complains that is not in the proper format because it is

[Alex] 
[James] 
[John]

in the console.

I want to combine them into the JSON payload described above so I can insert it into the datatable.

5
  • 2
    Are Alex, James and John objects or strings? Commented Apr 9, 2021 at 6:37
  • They are objects. Well, I parsed them from a file and stored it in data as [Alex, James, John] Commented Apr 9, 2021 at 6:43
  • It seems you misunderstood what JSON is. What you have is a Javascript array. You need to serialize it into JSON first, as JSON is a text format that can represent Javascript objects and arrays Commented Apr 9, 2021 at 6:45
  • @TostMaster Yes, you are right. I am using an API that I thought converts the parsing into JSON but it does not. Commented Apr 9, 2021 at 6:49
  • I still not understand sir, I read that was a javascript array, if they are objects the format is not valid sir, maybe you must check again your data, and edit your question again, so everyone can help you more again sir. Commented Apr 9, 2021 at 6:49

2 Answers 2

2

I think using the map method helps in your case!

If this is your JSON data = "["Alex","James","John"]". You can parse it with JSON.parse("["Alex","James","John"]"), this would results you an array object as ['Alex', 'James', 'John']

let personArray = ['Alex', 'James', 'John'];
let resultantArray = personArray.map(name => [name]);
console.log(resultantArray);

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Sign up to request clarification or add additional context in comments.

Comments

0

I would do this:

let ar = ["Alex", "James", "John"]
let ar1 = ar.slice(1)
let ar2 = ar.splice(0, 1)

console.log([ar2, ar1])

This solution assumes that you have already parsed your json into a Javascript array

Comments

Your Answer

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.