I have a json array of objects and want to find a way to get the property names into another array.
[
{
"ID": 12345,
"SID": 1111,
"DataPoint1": [
{
"Name": "SD",
"Activity": "KT",
"Group":"Test"
}
}
]
I want to be able to extract all the property names of DataPoint1 into its own array:
New-->
[Name, Activity, Group]
I was looking into loadash but couldn't find anything. Any ideas? Thanks.
You could use _.keys(data[0].DataPoint1[0]) to get the keys as an array.
const data = [{
"ID": 12345,
"SID": 1111,
"DataPoint1": [{
"Name": "SD",
"Activity": "KT",
"Group": "Test"
}]
}]
console.log(_.keys(data[0].DataPoint1[0]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Answered my own question :)
This did the trick:
Object.getOwnPropertyNames(array[0].DataPoint1[0])
Related
This is response data from server
[{"username": "harry"}][{"id": 1, "name": "playlist1", "tag": "genre"}, {"id": 2, "name": "playlist1", "tag": "genre"}, {"id": 3, "name": "playlist3", "tag": "genre"}][{"1": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"2": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"3": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}]
With axios, data comes as a string in the format as above.
There are three arrays in the above string, and I want to extract each one separately and store it in a variable.
It doesn't converted to JSON. How can I get the data of username and the data of the second array? I tried to access it by index, but since it is a string format, it is accessed one by one letter
You should get response fixed as sugguested by #certainperformance and #ambianbeing, but if you can't and still want to extract data from this string response you can do it by doing something like this
const axiosResponse = `[{"username": "harry"}][{"id": 1, "name": "playlist1", "tag": "genre"}, {"id": 2, "name": "playlist1", "tag": "genre"}, {"id": 3, "name": "playlist3", "tag": "genre"}][{"1": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"2": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"3": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}]`;
const result = JSON.stringify(
JSON.parse('{ "data": [' + axiosResponse.split('][').join('],[') + ']}').data[1]
);
console.log(result);
The response you have posted, is not a string. It appears to be three arrays, each containing x amount of objects.
A string can be identified, by being enclosed in either double: " " or single qoutes: ' '.
You can identify the arrays by the opening and closing square brackets: [ ].
The objects can be identified by the opening and closing curly brackets: { }.
Here is a bit more readable version of your response. I have annotated each top level array, with a comment, for easier identification.
// array 1
[
{"username": "harry"}
]
// array 2
[
{ "id": 1, "name": "playlist1", "tag": "genre" },
{ "id": 2, "name": "playlist1", "tag": "genre" },
{ "id": 3, "name": "playlist3", "tag": "genre" }
]
// array 3
[
{
"1": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
},
{
"2": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af",
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
},
{
"3": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af",
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
}
]
The third array appears to contain an object, with a list within it. Like somebody else mentioned earlier, this seems like faulty data, and I would have a look at the source, instead of trying to parse it. That being said, it isn't impossible to loop through each list, and extract the data, but it wouldn't be the correct way of doing it.
my question is above and I am trying like for 45mins to extract the value under "distance" below, but I fail at every try. I hope you guys can help me.
{
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
So I need the value under rows --> elements --> distance then value. I tried something like this in JavaScript:
var payload = JSON.parse(body)
console.log(payload.rows["elements"].distance.value)
Thanks! :)
Süleyman Demir
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (object_name.property_name). You can access an array's element by typing the element index in square brackets next to the array's name (array_name[element_number]).
In our case we access the property "rows" which is an array of the object "payload" - payload.rows. Then we access the element number [0] of this array by typing [0] next to the property's name - payload.rows[0]. We get another object which has the property "elements" in it - payload.rows[0].elements . This property stores another array and we access its first element again -
payload.rows[0].elements[0]. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - payload.rows[0].elements[0].distance.value
Source https://eloquentjavascript.net/04_data.html
Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
Try like below
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
I don't know exactly what you want, but you can get the distance object with something like that:
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped!
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I have array of object tree
var tree = [{
"id": "1",
"name": "one",
"child": [],
}, {
"id": "2",
"name": "two",
"child": [{
"id": "21",
"name": "twentyOne",
"child": [],
},{
"id": "22",
"name": "twentyTwo",
"child": [],
}],
}, {{
"id": "3",
"name": "three",
"child": [],
},
}].
Which one is the best way to store array of objects in localStorage?
Is it better to use another format?
There are several methods:
getItem
getAllItem
removeItem
saveItem
But there are child arrays of objects. It means that I will use recursive search to find necessary object.
Save the data in LocalStorage as an array, or array of simple objects, but try to keep it DRY (don't repeat yourself). For example, if you have a list of people, keep an array of the people, but don't keep a separate variable for the count.
What you want is basically a "state". As long as you keep it minimal you will be fine. Then you can use lodash or underscore to find, merge, add, remove elements from that array.
Hi i have a return json data which returns the webservice
The structure of webservice is like that:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tag":"s_science"'
"tag":"s_maths"'
"tag":"s_arts",
{"uid": "5",}]})
I have three "tag" elements. but when we access the products.tag it gives always last element like:s_arts.
Is there any way to find out all the elements eg:s_science,s_maths,s_arts.
please help.
It is invalid json, your tag should be:
...,
"tag": ["s_science", "s_maths", "s_arts" ],
...
Then product.tag would be an array that you could access successfully
Regards
If you have multiple keys in the same object, you're going to get undefined behaviour. Only one will be preserved, and since pairs are not ordered, you can't guarantee which you'll get.
In short: the webservice is returning you faulty data. If multiple tags are expected, the service should return an array of values in the tag attribute:
...
"tag":["s_science", "s_maths", "s_arts"],
...
You need to send the tags as an array:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tags": [
"s_science"'
"s_maths"'
"s_arts"
],
{"uid": "5",}]})
Then you reference them as data.tags[0], data.tags[1], data.tags[2].
if your response is in this format
YourResponse = {
"products" : [
{"uid" :"5", ......., "whtever":"someval"},
{"uid" :"6", ......., "whtever":"someval1"}
]
};
you can use this
$(YourResponse).each(
function(objName, objValue) {
console.log(objName); // wil get object name like uid, whtever
console.log(objValue); // wil get object's value
});
so to get Tags you will have to take Tuan's suggestion; send them in array