I have the following object
var object = ["{
"a": "foo",
"b": "bar",
"c": "baz"
}
"]
I am interested in getting value a, but everything I have tried comes up undefined. I have tried object.a, object[0].a and object[a], I know it's something silly I am simply forgetting. Any help is greatly appreciated.
var object = ['{ "a": "foo", "b": "bar", "c": "baz" }'];
console.log(JSON.parse(object[0]).a);
your array should look like this
var object = [{
"a": "foo",
"b": "bar",
"c": "baz"
}];
remove the double quotes so that you can access the object inside the array or else you can use the JSON.parse() just like #Daniel did
Related
I have data structure similar like this
{"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]}
I would like to change every id to null.
I know I could do loops and manually assign null to id. Is there any easy way to do this in JavaScript?
Without changing the object to a JSON string, you could use recursion:
function clearIds(obj) {
if ("id" in Object(obj)) obj.id = null;
Object.values(Object(obj)).forEach(clearIds);
}
// Demo
let obj = {"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]};
clearIds(obj);
console.log(obj);
This mutates the given object in place.
For fun: the same function as a one-liner:
const clearIds = o => "id" in Object(o) && (o.id = null) || Object.values(Object(o)).forEach(clearIds);
// Demo
let obj = {"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]};
clearIds(obj);
console.log(obj);
Bravo's comment was illuminating so I hope they don't mind if I expand on it here.
Turn the object into a string.
Parse it back into an object again.
What I didn't know is that JSON.parse has a "reviver" function that allows you to transform the string value as it's being parsed.
const data = {"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]};
// Turn the data into a string
const str = JSON.stringify(data);
// Parse the string back to an object
// but using the reviver function to turn the value of any id
// keys to null
const newObj = JSON.parse(str, (key, value) => key === 'id' ? null : value);
console.log(newObj);
I'm trying to figure out if a array contains a specific index or not using the following codelines:
var array1 = [{ "abc": 123, "def": [{"a": 1, "b": 2, "c": 3}, {"a": 3, "b": 2, "c": 1}]}]
console.log(array1.includes('def'));
The array contains "def" so the console should actually return true if I define the array in the following way:
var array1 = [{ "abc": 123, "def": [{"a": 1, "b": 2, "c": 3}, {"a": 3, "b": 2, "c": 1}]}]
Defining it the other way, like:
var array1 = [{ "abc": 123 }]
should return false.
The code above therefore does not work correctly, does anyone have a idea whats causing it to respond a wrong boolean?
I appreciate any kind of suggestions!
The proper method would be array1.some(n => n.hasOwnProperty('def')). See that there is no def in array, but rather object that contains def property
Array.includes returns a boolean based on whether (x) is a value in the given Array, not keys. If you want array1.includes('def') to return the other parts then you must do Object.keys(array1[0]).includes('def')
That is because you do not indicate array you think of.
If you console.log
Object.getOwnPropertyNames(array1), array1 is an array of one object. To get proper result you have to check if the object inside have the def property, so:
array1[0].hasOwnProperty('def') // returns true
The problem here is you try to access an element that is in an object and this object is in a list. To acces the list element, you need to specify its index (here 0). Then you can access the object keys with Object.keys.
var array1 = [{ "abc": 123, "def": [{"a": 1, "b": 2, "c": 3}, {"a": 3, "b": 2, "c": 1}]}]
Object.keys(array1[0]).forEach((element) => {
if(element === "def") console.log(true);
})
I have the following JSON variable:
var jsonObj= { "ClassA": { "A": "111", "B": "222", "C": "333", "D": "444", "E": "555", "F": "666", "G": "777" }, "ClassB": { "A":"22","B":"33","C":"44","D":"55","E":"66","F":"77","G":"AAA" }};
How do I get the class A value for key A ?
I am writing a function to allow for me to get these, something like:
function getDisplayValue(turnOverBracketCategory, classTypeAorB) {
if(classTypeAorB == "A") {
alert("1");
return jsonObj.ClassA[turnOverBracketCategory];
} else {
alert("3");
return jsonObj["ClassB"].key[turnOverBracketCategory];
}
}
Where turnOverBracketCategory is the key ("A", "B", etc.) and the classTypeAorB defines if using "ClassA" or "ClassB".
You can access ClassA + A doing this:
jsonObj.ClassA.A
will return 111
You can get the keys like this
Object.keys( jsonObj.ClassA );
will return "A","B"....
Thanks! Not exactly what I wanted, but good to know that I can also access the key. Althouh, what I am looking for is the value...
I already had the answer, the issue was that the variable was not being correctly populated.
Cheers.
To get the value I would do the following
jsonObj.ClassA[turnOverBracketCategory]
or
jsonObj.ClassA["A"]
This is silly but I can't figure it out.
I have a simple object in JS:
var objSyntax = [ {"a": "1"},
{"b": "2" },
{"c": "3"} ];
I want to call 1 when theid is equal a, etc.
Here is the notation I tried which did not work:
objSyntax[theid];
What am I doing wrong?
you could change your object to reflect something like:
var objSyntax = {"a": "1",
"b": "2" ,
"c": "3"};
objSyntax[theId];
or iterate through the array of objects you have posted:
var objSyntax = [ {"a": "1"},
{"b": "2" },
{"c": "3"} ];
With how you have it set up right now, you would access it like this
objSyntax[0][theId]
I have wasted two days on this and I can't take it anymore. I am getting well formed JSON data from my $.ajax call. Sample below...
"results":[
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}"
]
I have attempted to access the values in this single array of JSON objects and just can't figure it out. Here's my code below...
success:function (data) {
/*
$.each(data.results, function(i, val) {
console.log(i, val);
});
*/
$('a.previewUrl').each(function (i) {
var res = jQuery.parseJSON(data.results[0]);
var previewUrl = $(this);
if(previewUrl.attr("href") == '') {
previewUrl.attr("href", res[i].d);
}
});
} // end success
The console.log iteration over each JSON object in the array prints out fine but I think I have tried a dozen different ways to grab these values in the $.each() loop. What I am missing?
Your Json isn't valid. Try putting it through jsonlint and see what happens.
I think this could be what you were aiming for:
{
"results": [
{
"a": "data",
"b": "data",
"c": "data"
},
{
"a": "data",
"b": "data",
"c": "data"
},
{
"a": "data",
"b": "data",
"c": "data"
},
{
"a": "data",
"b": "data",
"c": "data"
}
]}
and if you're using jQuery's $.getJSON function, you don't need to parse your data or if you're using the $.ajax function, set the datatype to json so it wil parse the data for you.