javascript - How to split JSON array into separate arrays for DataTables - javascript

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.

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

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

Related

add keys to a json file, remove duplicates and write to json file in javascript

I want to add data from another Json file to another without overwriting the existing one. I just can't get any further, the console always gives me the following:
Console output
Data
string
[
"follow1",
"follow2",
"follow3",
"follow4",
"[\"follow5\",\"follow6\",\"follow7\",\"follow8\",\"follow9\"]"
]
This is my code, I would like to add the data but without square brackets and without backslashes. It would be really nice if someone could help me. Thanks very much
const user = require('./user.json');
const oldUser = user.user_follwos["user1"];
const data = require('./data.json');
const toAdd = JSON.stringify(data);
const result = JSON.stringify(toAdd);
oldUser.push(...toAdd.split(' '))
const newData = JSON.stringify(oldUser, null, 4)
console.log('\nData \n' + typeof newData + ' \n' + newData);
and here are my json files
//user.json
{
"application_id": "123546789",
"user_follwos": {
"user1": [
"follow1",
"follow2",
"follow3",
"follow4"
],
"user2": [
"followA",
"followB",
"followC",
"followD"
]
},
...
...
}
//data.json
[
"follow5",
"follow6",
"follow7",
"follow8",
"follow9"
]
You should convert your data structure to JSON exactly once at the very end, immediately before you write the result to the file.
As it stands, you are converting everything to JSON at every opportunity. So every time you try to add, say, an array to your data structure you instead add a string of JSON representing that array.
You don't need to stringify your data variable because it is a javascript object so you can just concat it to the end of your existing user array.
const user = require('./user.json');
let oldUser = user.user_follwos["user1"];
const data = require('./data.json');
oldUser = oldUser.concat(data);
const newData = JSON.stringify(oldUser, null, 4);
console.log('\nData \n' + typeof newData + ' \n' + newData);
The concat method creates a new array object so you could assign the result to a new variable without overwriting your existing "oldUser" variable.
Data
string
[
"follow1",
"follow2",
"follow3",
"follow4",
"follow5",
"follow6",
"follow7",
"follow8",
"follow9"
]
First of all to do something you need both data in json
Make 2 arrays
Remove duplicates
Then push data without duplicates.
Put everything together
let allTogether = data.push(...oldUser);
Create unique array
uniq = [...new Set(allTogether )];
Finally set this unique data to specific key
user_follwos.user1 = uniq
Hope this is what you need
Update with example
let user = {
"application_id": "123546789",
"user_follwos": {
"user1": [
"follow1",
"follow2",
"follow3",
"follow4"
],
"user2": [
"followA",
"followB",
"followC",
"followD"
]
}
};
let data = [
"follow5",
"follow6",
"follow7",
"follow8",
"follow9"
];
let oldUser = user["user_follwos"]["user1"];
console.log(`This is old user array`);
console.log(oldUser);
let allTogether = [];
allTogether.push(...data)
allTogether.push(...oldUser);
console.log(`After we put all together`);
console.log(allTogether);
uniq = [...new Set(allTogether )];
console.log(`Getting unique values`);
console.log(uniq);
oldUser = uniq;
console.log(`Now olds user is`);
console.log(oldUser);

Convert array string to array for mapping data

Here is my problem
const data = "[\"https://i.imgur.com/PAYXC2n.jpg\",\"https://i.imgur.com/bEfjjxA.jpg\"]";
I want to convert this string to array,
expected result will be :
res =["https://i.imgur.com/PAYXC2n.jpg","https://i.imgur.com/bEfjjxA.jpg"]
I use it for mapping data in React JS project, so i need to convert this string to array.
Just parse it from JSON:
const
data = "[\"https://i.imgur.com/PAYXC2n.jpg\",\"https://i.imgur.com/bEfjjxA.jpg\"]",
parsed = JSON.parse(data);
console.log(parsed);
Do it:
const dataArr = JSON.parse(data);. This will parse as to object, which is your array (With out "")

Parsing JSON object in react js

I am getting API response as:
[{"subject1": "English", "subject1": "Maths"}]
I want to store the values (English and Maths) into an array without keys like:
subject = ["English", "Maths"]
maybe this solve your problem:
// if you have variable number of subject
let res = [{"subject1":"English", "subject2":"Maths"}]
let subjects = []
for(prop in res[0]){
subjects.push(res[0][prop])
}
console.log(subjects)
Does this solve your problem?
subject = [];
subject.push(Object.values(response));
Given an array of objects:
[{"subject1":"English"}, {"subject1":"Maths"}]
Use this:
let res = foo.map(e => e.subject1)
console.log(res) // prints ["English", "Maths"]

PUSH JSON items to array

I have this JSON string
{"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]}
I want to push it's items to a jQuery array.
I already tried JSON.parse.
Normally I can push parameters like this:
MyArr.push(['Task','Hours per Day']);
MyArr.push(['Work','11']);
MyArr.push(['Eat','6']);
and so on.
How can I do the same with the JSON string?
Can you not just parse the JSON into an object and loop through?
var json = '{"Task": ["Hours per Day"],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]}'
var obj = JSON.parse(json);
MyArr = []
for (var key in obj) {
MyArr.push([key, obj[key][0]])
}
console.log(MyArr)

How to take json response in an array

I am making a ajax request in jquery and in return getting the response but not as an array.
{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}}
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
I want to merge the above two response and create an array something like this :
{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
Please suggest how to do it. I want to take it in array and store it locally may be in config varaible get:[] and then access somewhat like config.get[data["seriesId"]].
you need to convert your response into an array of objects:
var response = [
{"ErrorCode":0,...},
{"ErrorCode":0,...},
{"ErrorCode":0,...},
]
in actual:
jsonResponse = [
{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}},
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
]
then loop through:
var newArray = []
for(var i=0;i<jsonResponse.length;i++){ //loop through items
var stats = jsonResponse[i].SeriesSocialStats;
for(key in stats){ //loop through "SeriesSocialStats" numbers
newArray.push(stats[key]);
}
}
so it will be like:
newArray = [
{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},
{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
]
You could do
var obj1 = {"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}};
var obj2 = {"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}};
var arr = [];
arr.push(ob1.SeriesSocialStats);
arr.push(ob2.SeriesSocialStats);
Best way convert your server response to array structure, like mentioned by Joseph, instead of doing double processing from object to array.

Categories

Resources