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"]
Related
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);
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
I have an API that returns an array and I need to create some charts with that data.
The issue is the way they are returned and how I map that into the chart.
The data looks like this:
[["United States",258],["Germany",88],["France",68]]
And I want to save this data into their own variable like the following:
var country = ["United States", "Germany", "France"]
var count = ["258", "88", "68"]
How can I achieve this? I wasn't sure how to explain this the correct way, so please do correct me if needed.
You can do it via Array.protoype.map()
let apiResponse = [["United States",258],["Germany",88],["France",68]];
let countries = apiResponse.map(x => x[0])
let counts = apiResponse.map(x => x[1])
Just iterate over the array and put the data in your arrays, something like:
const country = [];
const count = [];
serverArray.forEach((entry) => {
country.push(entry[0]);
count.push(entry[1]);
})
And please don't do 2 loops for something you could do in just 1 loop.
using this:
let country = [], code = []
let data = [["United States",258],["Germany",88],["France",68]]
data.forEach(d => {
country.push(d[0])
code.push(d[1])
})
console.log({country, code})
You can achieve this by using a single loop. No need to use two map functions.
let response = [["United States",258],["Germany",88],["France",68]];
var counts = [], countries = [];
response.forEach((item) => {
countries.push(item[0]);
counts.push(item[1]);
});
As a ReactJS newbie, I tried to parse RestfulAPI JSON reponse, But, I couldn't retrieve all elements. While trying to access text.subjects.code and text.subjects.description, it returns null. However, I could successfully access text.id and text.name.
JSON response is given below.
[
{
"id":95822,
"name":"Alex",
"subjects":[
{
"code": "101",
"description": "Course 101"
}
]
}
]
Kindly advise.
You can do iteration in many ways and few ways which I always prefer using .forEach and .map
If you need new array then go with .map. Because map returns a new array
const dataArray = text.subjects.map(subject => {
let obj = {};
obj.code = subject.code;
obj.description = subject.description;
return obj;
});
//dataArray will contain all the objects
There is also a Different way of doing map
const dataArray = text.subjects.map(subject => (
let obj = {};
obj.code = subject.code;
obj.description = subject.description;
return obj;
);
Or if you want to just iterate the data then use .forEach. forEach doesn’t return an array
let array = [];
text.subjects.forEach(subject => (
let obj = {};
obj.code = subject.code;
obj.description = subject.description;
array.push(obj);
));
if You check subjects is an array and you are not getting value from it, try
text.subjects[0].code
Because subjects is an array and you should map subject like the following:
text.subjects.map((subject) => {
console.log(subject.code, subject.description);
})
or directly get the index that you to want like the following:
text.subjects[0].code
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.