Get Value from Object using another value - javascript

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]

Related

How to change values of every id in this nested object array?

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);

Javascript array includes

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);
})

Access Variable in JS Array

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

How to create an obj with multiple values and randomly choose values without repeating in jQuery/JS

Is this the way to create and obj to store multiple values, if so, how would you randomly choose two or three values without repeating again until all values were outputted from the array?
I want to randomly get the values like this
E.g., if row three was randomly chosen then the results should be;
gg hh ee
I.e., I want to randomly output one array with its values, that would be like three hints for a question, so, the user would have to enter the answer and then compare the values to see if it matches.
JS
var list = {
"one": [ { "a": "aa", "b": "bb", "c":"cc" } ],
"two": [ { "d": "dd", "e": "ee", "f":"ff" } ],
"three": [ { "g": "gg", "h": "hh", "e":"ee" } ],
"four": [ { "j": "jj", "k": "kk", "l":"ll" } ],
"five": [ { "m": "mm", "n": "nn", "o":"oo" } ]
};
And also if I decide just to output one value at a time, how can I do that?
Currently if row three was randomly selected it would output an array with one entry (your object), like so:
[[object Object] {
e: "ee",
g: "gg",
h: "hh"
}]
We can just use arrays and the Fisher-Yates function, which can be found here: https://github.com/coolaj86/knuth-shuffle
This should give us a randomized array of the values.
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
If you need the keys associated with the value, just use an array of objects. Instead of using "one", "two", "three", etc to identify each set, we can just use the index of the object in the array. For example:
var list = [
{"a" : "aa", "b": "bb", "c" : "cc"},
{"d" : "dd", "e": "ee", "f" : "ff"},
{"g" : "gg", "e": "hh", "i" : "ii"},
];
Then we'd use:
shuffle(list);
console.log(list[0]);
which should give us a randomized array of objects. Each time it ran it'd get a random object:
[object Object] {
e: "hh",
g: "gg",
i: "ii"
}
[object Object] {
e: "hh",
g: "gg",
i: "ii"
}
[object Object] {
a: "aa",
b: "bb",
c: "cc"
}
Just grab the first item in the array after shuffling it, list[0] and use for-in loop to get the values:
var randomResult = list[0];
for (key in randomResult){
console.log(randomResult[key];
}
If you don't need the key associated with the value, i.e., "a" with "aa", and you just wanted to get a random selection from your values you can use an array and the Fisher-Yates (aka Knuth) Shuffle function.
For example:
var list = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']
We can then apply it to the array
shuffle(list)
and we'd get an array with the same values (no repeating) that is randomized and can be iterated over.
["cc", "ee", "bb", "gg", "aa", "ff", "dd"]
If you need values to be grouped together but you don't need the keys, i.e., you need 'aa', 'bb', 'cc' to always be returned together, you can use an array of arrays AKA a multidimensional array.
var list = [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['gg', 'hh', 'ii']];
If we run the sorted function along with a little extra code we can get the three values
function sortedMulti(array){
sorted(array);
return array[0]
};
With this we'd get a random set each time.
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["gg", "hh", "ii"]
["gg", "hh", "ii"]
This would randomize the array, meaning you'd get a random set at the index 0 of the main array. You can then either return it (like I have) or iterate through the items in the array with a for loop to get each value.

How to get json child value of array key pair in javascript?

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"]

Categories