I've been developing a web application where I'm receiving data in this format, from a node server:
"{""elements":[{"10sr2b2":{"total":0,"bad":22,"clients":["fc8e7f","fc8e7e"],"zone":"101900"}}]}"
The poblem is this data is an array key-value called "elements" where "10sr2b2" is the key of the first element of the array.
So when I call $.parseJSON() method, this return an object like this:
elements: Array[1]
0: Object
10sr2b2: Object
zone: "101900"
clients: Array[2]
0: "fc8e7f"
1: "fc8e7e"
length: 2
__proto__: Array[0]
bad: 22
total: 0
Where "10sr2b2" it's supposed to be the key and it's an object and I need to get this value somehow.
Can you help me?
You could use Object.keys to get the object keys.
var keys = Object.keys(data.elements[0]);
Can you change the format from the node server? It needs to send something more like:
"{""elements":[{"key": "10sr2b2" "value": {"total":0,"bad":22,"clients":"fc8e7f","fc8e7e"],"zone":"101900"}}]}"
If you know you'll always only have one key for each item, you can use a for..in loop that immediately breaks, for example
var i, key, obj = $.parseJSON(/*...*/);
for (i = 0; i < obj.elements.length; ++i) { // loop over elements
for (key in obj.elements[i]) break; // get key
// now can access
obj.elements[i][key]; // Object
}
Related
Goal: For each key, assign every value to an array.
Use case: I have to be able to search using all possible values simultaneously. As seen at the bottom, a possible key:value search would be:
"LocationNumber": [1,2,3,4]}
The problem: Object SettingOptions is a nested array.
This is how I log each key within a given index:
//Defines array 'keysArray'
const keysArray = [];
pm.test("array of SettingsOptions[0] keys", () => {
arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions[0]; //object 'SettingOptions[0]' calls 1st settingoption
//For each property in array, add the property to 'keysArray'
for (var property in arrayOfObject) {
keysArray.push(property)
}
console.log(keysArray)
});
Response:
(11) ["LocationNumber", …]
0: "LocationNumber"
1: "StoneCount"
2. ....
....
9: "Shape"
10: ...
To create an array of values from a given property:
pm.test("array of SettingsOptions objects", () => {
arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions;
let arrayLocationNumber = arrayOfObject.map(a => a.LocationNumber);
// console.log(Object.values(arrayLocationNumber));
});
Response:
[1, 2, 3, 4]
What I'm looking for:
There is a lot of variation in the data I'm pulling from. So I need to be able to automagically pull values to be able to reference them in subsequent requests. An acceptable response could look something like:
0.{"LocationNumber": [1,2,3,4]}
1....
2.......
3.{"Shape": ["Center","Halo","Accent 1","Accent 2"]}
I've been at this for a bit trying to come up with a solution. I have tested a handful of stack solutions to iterate through nested objects but haven't gotten this to work correctly. My data structure is below.
I've been trying to first off iterate through nested objects which this stack seemed to be similar to mine.
Iterate through Nested JavaScript Objects
However, when I'm in my for loop getting access to geo, value object to grab all of its properties, ip, hostname, city etc I'm coming up empty handed with undefined. Here's a code snippet of what I've tried below.
I'm trying to take all of the keys and values in this entire object and stringify them into a beautiful parameter string to send over to the server in an ajax request.
for (var i = 0; i < myarray.length; i++) {
var o = myarray[i];
if (o.name === "geo") {
o.value.ip;
}
}
0: {name: "firstname", value: "John"}
1: {name: "lastname", value: "Smith"}
2: {name: "email", value: "asddas#gmail.com"}
3: {name: "password", value: "asdsdadasads"}
4: {name: "paypal_email", value: "asdsa#gmail.com"}
5: {name: "phone", value: "1234567894"}
6: {name: "geo",value: "
{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
__proto__: Object
length: 7
__proto__: Array(0)
The problem is that the structure of the geo object is odd:
name: "geo",value: "{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
The value looks to be a string in JSON notation. You'll have to parse it first in order to look up properties on it:
if (o.name === "geo") {
const nestedObj = JSON.parse(o.value);
console.log(nestedObj.ip);
}
You might also consider fixing whatever's serving you that object so that the value is an actual object - if that's possible (it may not be, but it would make the code make a lot more sense).
You can also consider using .find instead of a for loop, to make the code shorter and more elegant:
const json = myarray.find(({ name }) => name === 'geo').value;
const nestedObj = JSON.parse(json);
(if the geo object may not exist, test for undefined first, of course)
It would appear that the value field for the object with the name of "geo" is a JSON string.
Because the value is a string, you won't be able to directly access the ip field without first parsing that string to an object:
for (var i = 0; i < myarray.length; i++) {
var o = myarray[i];
if (o.name === "geo") {
/* "Convert" the JSON string in o.value to the corresponding object */
const valueObject = JSON.parse(o.value);
/* The ip field can now be accessed from the valueObject, parsed from
the JSON string in o.value */
console.log(valueObject.ip);
}
}
I have an array object where there are key value pairs. I am trying to get the keys in that array using a loop but I am getting only 0. What is the problem with my code.
var strj = '{"name":"John","age":"30","cars":
[ {"type":"car", "year":"1998"},
{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type=='car');
Value of care
0:{type: "car", year: "1998"}
length:1
__proto__:Array(0)
Loop
for (var key in care){
if(care.hasOwnProperty(key)){
console.log(key)
}
}
care is a array type so you cannot do for (var key in care). You need to do for (var key in care[0]). This is because for (var key in care) will look for the key value in care and since it is a array it will always take 0 as a value in key(as you have only one object in array and its index is 0). That is why you got 0 in console.log.
var care =[{type: "car", year: "1998"}];
for (var key in care[0]){
if(care[0].hasOwnProperty(key)){
console.log(key)
}
}
care.forEach( ( singleCar ) => {
for ( var key in singleCar ){
console.log(key);
if( care.hasOwnProperty( key ) ){
console.log(key);
}
}
})
forEach will give you all the objects one by one. so you can check them.
As others have solved the issue, might i make a suggestion - Object.keys () gives an array of the keys for a given object. Since you are getting your filtered object and simply want its keys - the following will achieve that. Note that this is only using the code after you have filtered the original and have gained the "care" object.
As an aside, note that object.values() will give you an array of the values in a given object and object.entries() will give you arrays of the key / value pairing.
var care = {type: "car", year: "1998"};
var keys = Object.keys(care)
console.log(keys) // gives ["type","year"]
filter() method returns a Array of matches.
var care = myobj.cars.filter(c => c.type=='car'); // So, this returns an array.
care.forEach(element => {
console.log(Object.keys(element)); //Prints keys of each element
});
Well actually there is no problem in your code at all. But you just misunderstood the use of javascript filter. Javascript filter() creates new array that's why you are getting 0 as key. If you want to get only one matching element then find() is what you should use.
var strj = '{"name":"John","age":"30","cars":[{"type":"car", "year":"1998"},{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type == 'car'); // returns array
var care = myobj.cars.find(c => c.type == 'car'); // returns first matching object
var care = myobj.cars.findIndex(c => c.type == 'car'); // returns first matching index
Javascript filter() method => Read Here
Javascript find() => Read Here
Javascript findIndex() method => Read Here
I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);
I have this code:
var mydata = [];
$.each(divs, function(idx, val){
var dID = $(val).attr("id");
mydata[dID] = new Array();
mydata[dID].push({'newproperty':"newvalue"});
});
This gives me results like this:
25465: Array[1]
0: Object
newproperty: "newvalue"
__proto__: Object
length: 1
__proto__: Array[0]
I want it like this:
25465: {
newproperty: "newvalue"
}
Any idea?
I want it like this
You've put in an unnecessary extra level of indirection.
// Create a blank object
var mydata = {};
$.each(divs, function(idx, val){
var dID = $(val).attr("id");
// Add/overwrite a property on that object with the name from the
// variable dID, and the value being a new object with the properties
// shown -- I assume those properties are just examples, since as
// given they're identical on each pass...
mydata[dID] = {'newproperty':"newvalue"};
});
Since you're not using the Array features of arrays, don't use an array, just use an object ({}). Since your goal is to have keys like 25465 refer directly to objects, don't create an array within the array/object, just assign to that key.