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);
})
Related
I looked in the js docs and while studying the doc it mentioned in object.assign()
If the source value is a reference to an object, it only copies the reference value.
In my below snippet, one alters the original object and the other doesn't
var objA = {
a: 1,
b: {
c: 2,
d: {
e: 3,
},
},
}
var objC = { t: 1 };
//why this works i.e adds a to objEmpty
// var objEmpty = Object.assign({}, { objC }); //this would add a prop to the objEmpty object
//this doesnt work i.e doesnt add a to objEmpty
var objEmpty = Object.assign({}, objC); //this will not
objC.a = 3;
console.log(objC);
console.log(objEmpty);
I am getting my head around how really things work by trying different scenarios and I believe that it is something related to reference but how?
Another example from the docs
const obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
obj1.a = 1;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
obj2.a = 2;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
obj2.b.c = 3;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}```
why does js behave this way? why the 3 got changed but the other didn't?
Thanks in advance :)
why does js behave this way? why the 3 got changed but the other
didn't?
Because Object.assign() actually does Shallow Copy, you need to do Deep Copy
To do deep copy of an object.
There are bunch of ways, The most common and popular way is to use JSON.stringify() with JSON.parse().
const oldObj = {a: {b: 1}, c: 2};
const newObj = JSON.parse(JSON.stringify(oldObj));
oldObj.a.b = 3; // will not affect the newObj
console.log('oldObj', oldObj);
console.log('newObj', newObj);
Note: There's a new JS standard called structured cloning. It works on all browsers:
method creates a deep clone of a given value using the structured clone algorithm.
const clone = structuredClone(object);
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 was just going through the MDN documentation for set , and how it works , coming to the part of how to iterate over a set , i saw the following examples:
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
for (let item of mySet) console.log(item);
And
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
for (let item of mySet.values()) console.log(item);
And
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
//(key and value are the same here)
for (let [key, value] of mySet.entries()) console.log(key);
Just to confirm , does this mean that when using set the keys and values are the same ?
The entries() method returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order [...].
MDN docs
So no, Sets don't have keys at all, however .entries() lets you believe so for having consistency between Maps and Sets.
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
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"]