Javascript Objects - Check for and loop through arrays in object [duplicate] - javascript

This question already has answers here:
Traverse all the Nodes of a JSON Object Tree with JavaScript
(17 answers)
Closed 1 year ago.
I am trying to loop through an object literal and if a property is an array, I want to loop through that as well. The friends property of this object is an array, how would I test to see if it's iterable, then loop through it?
Thanks in advance,
firstName: 'Jonas',
lastName: 'Schmedtmann',
age: 2037 - 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven'],
};
const myObj = Object.entries(jonas);
for (const [key, val] of myObj) {
//Some conditional statement here testing for an interable
//Then loop through it to the console.
console.log(key, val);
}

All arrays are instance of the Array class in Javascript so you can use var instanceof Array which returns a boolean to check if an element is an array or not, then iterate through it as you wish
const obj = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
age: 2037 - 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven'],
};
const myObj = Object.entries(obj);
for (const [key, val] of myObj) {
//Some conditional statement here testing for an interable
//Then loop through it to the console.
if (val instanceof Array) {
console.log('element is an array, printing now')
print(val);
} else
console.log(key, val);
}
function print(ar) {
ar.forEach(x => console.log(x));
}

Related

How to use the filter method to remove an object from an array

For example:
const array = [
{
name: JB,
age: 28,
dob: '12-17-1996'
}
{
name: Jamey,
age: 57
dob: '9-13-1965'
}
{
name: Jayla,
age:30,
dob: '11-18-1992'
}
]
How would I use the filter method (and without any arrow syntax involved) to remove one of these objects from the array and iterate the updated array in Javascript?
I tried it in a for loop but it just keeps giving me undefined.
You can use Array#filter to obtain all elements whose name do not match the name of the object you want removed.
const array=[{name:"JB",age:28,dob:"12-17-1996"},{name:"Jamey",age:57,dob:"9-13-1965"},{name:"Jayla",age:30,dob:"11-18-1992"}];
let remove = 'Jamey';
let filtered = array.filter(function(obj){
return obj.name !== remove;
});
for (const obj of filtered) console.log(obj);

Javascript Map() object has confusing behaviour [duplicate]

This question already has answers here:
Object copy using Spread operator actually shallow or deep?
(4 answers)
Closed 6 months ago.
I have a use case that I thought the Map object would be perfect for but there is confusing behaviour that appears to me as a bug, but Im after any information as to why this happens and possibly a solution to the behaviour.
For instance, say I have 2 objects:
const obj1 = { name: "John" };
const obj2 = { name: "Jane", age: 35 };
And I have defined and extra object for extra properties to add to both objects later:
const extProps = { gender: "unspecified", children: [] };
Create a new Map object and add the 2 objects:
const map = new Map();
map.set(obj1.name, obj1);
map.set(obj2.name, obj2);
Due to the objects being reference types I can assign the extra props like so:
Object.assign(obj1, { ...extProps });
Object.assign(obj2, { ...extProps });
Now I can get the values from the map using the keys like:
const johnObj = map.get("John");
const janeObj = map.get("Jane");
And the object have all the extra props like expected. The following statements update the individual objects in the map:
janeObj.gender = "female";
johnObj.age = 45;
Here is where the confusing behaviour I see is happening...
If I add an entry to the children array of either objects, it updates both
johnObj.children.push("jack");
obj2.children.push("jenny");
name: "John"
gender: "unspecified"
children: ["jack", "jenny"]
age: 45
name: "Jane"
age: 35
gender: "female"
children: ["jack", "jenny"]
What am I missing??
Like Konrad said in his comment, "arrays are also objects and are reference types".
The issue is that the spread operator (...) only goes on level deep, so for the array in extProps, is it not copied, it is the same one.
To solve this you can use a recursive function to "deep copy" an object.
Here is an example of a deep copy function:
const deepCopy = objIn => {
if (typeof objIn !== 'object' || objIn === null) return objIn;
let objOut = Array.isArray(objIn) ? [] : {};
for (const key in objIn) {
objOut[key] = deepCopy(objIn[key]);
}
return objOut;
}

Looping through an object without using Object.entries() on each key of the inner object [duplicate]

This question already has answers here:
How to loop through a plain JavaScript object with the objects as members
(28 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 months ago.
I would like to know how to loop through a nested object without specifying keys. I mean just to take the name of the object to do the loop. Is there any method to achieve it?
You can see at the bottom what I tried. It actually works, but I want to know if there is a way to do this without mentioning the keys(hero, monster)
Object to loop through:
const characterData = {
hero: {
name: "Wizard",
avatar: "images/wizard.png",
health: 60,
diceCount: 3,
currentDiceScore: []
},
monster: {
name: "Orc",
avatar: "images/orc.png",
health: 10,
diceCount: 1,
currentDiceScore: []
},
};
Object.entries(characterData.hero).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
You can first iterate over Object.values() which, in this case, are the nested objects hero, monster and so on.. using Array.prototype.forEach(), and then your code that iterates over Object.entries() again using Array.prototype.forEach()
But notice that in the callbackFn function is used the square brackets Destructuring assignment and inside the console.log() Template literals (Template strings):
const characterData = {hero: {name: "Wizard",avatar: "images/wizard.png",health: 60,diceCount: 3,currentDiceScore: []},monster: {name: "Orc",avatar: "images/orc.png",health: 10,diceCount: 1,currentDiceScore: []},}
Object.values(characterData)
.forEach(o =>
Object.entries(o)
.forEach(([k, v]) =>
console.log(`${k}: ${v}`)))

how do I create dictionary of dictionaries in Javascript

In python, a dictionary of dictionaries can be created
mainDict = {}
mainDict[subDict][subDict_Key1]=[subDict_value1]
I want to create a similar dictionary of dictionaries or array of dictionaries in Javascript.
I have check multiple threads on SO but yet to find anyone.
I don't know the dictionaries yet, they will be added dynamically. For example I want to be able to create
var mainDict = {}
and then be able to add dict1,2,3... below
Dict1 = {name: sam, age:26, city:NY}
to mainDict so that I can iterate through mainDict and retrieve all dictionary with their respective keys and values
how do I do this in Javascript?
You first need to create the "sub-dictionary" before assigning values to it:
var mainDict = {}
mainDict[subDict] = {} // This was missing
mainDict[subDict][subDict_key1] = subDict_value1
Of course, if the values are static, this can be done in a more concise way:
var mainDict = {
dict1: {
name: 'sam',
age: 26,
city: 'NY'
},
dict2: {
name: 'joe',
age: 27,
city: 'LA'
}
}
console.log(mainDict.dict2.name) // joe
Then you can iterate through the inner dictionaries as you wish:
for (const key in mainDict) {
console.log(`${key} has name ${mainDict[key].name}`)
}
...or, alternatively:
for (const [key, subDict] of Object.entries(mainDict)) {
console.log(`${key} has name ${subDict.name}`)
}

Convert this object into array of key value pair [duplicate]

This question already has answers here:
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 19 days ago.
if we create one object like
const userDetails={firstname:'karan',lastname:'khimani'}
then expected output like
[["firstname", "karan"], ["lastname", "khimani"]]
How did i convert this?
Use Object.entries:
const userDetails = { firstname: "karan", lastname: "khimani" };
const arr = Object.entries(userDetails);
console.log(arr);
I believe this is an ES7 feature - so if you need to support older browsers, use map with Object.keys:
var userDetails = { firstname: "karan", lastname: "khimani" };
var arr = Object.keys(userDetails).map(function(key) {
return [key, userDetails[key]]
});
console.log(arr);
So what you want to do is create an array, which contains keys and values as arrays.
You should have a look at Object.keys and Object.entries.
Soluce are below, but try to find it yourself first looking at the documentation of the functions I've given you.
const userDetails = {
firstname: 'karan',
lastname: 'khimani'
};
const transformed = Object.keys(userDetails).map(x => [x, userDetails[x]]);
console.log(transformed);
Why not always use Object.entries? Because It's not well supported on every browser.
const userDetails = {
firstname: 'karan',
lastname: 'khimani'
};
const transformed = Object.entries(userDetails);
console.log(transformed);

Categories