As in the passage of the loop object, whether the object property of another object?

Good evening! There is code:
const data = {
 user: 'ubuntu',
 hosts: {
 0: {
 name: 'web1',
},
 1: {
 name: 'web2',
 null: 3,
},
},
};

Is it possible when using a loop to the properties of the hosts to understand what is the object?
I just need in this case to add to the body of the loop(or conditions) after the object(in this case data), or .object or [property].
By the way, by what method, I will be able to add? I need to add any data.hosts or data[property]
April 3rd 20 at 18:28
2 answers
April 3rd 20 at 18:30
Solution
Is it possible when using a loop to the properties of the hosts to understand what is the object?


typeof()

console.log(typeof({}));
// object


for (var key in data) {
 if(typeof(data[key]) == "object") {
 console.log (key + "is object");
}
}



I just need in this case to add to the body of the loop(or conditions) after the object(in this case data), or .object or [property].


do not understand what you are saying...

By the way, by what method, I will be able to add? I need to add any data.hosts or data[property]


to add WHAT to add WHERE??

and recording data.hosts or data["hosts"] are equivalent.

add to data.hosts another item?

see JavaScript: How to add a new item to the object?

data["hosts"][2] = {name: 'web3'}

but here a complication arises with the definition of the following key number, because it is NOT an array!
with an array would be easier.

data["hosts"][data["hosts"].length] = {name: 'web3'}
// or
data["hosts"].push( {name: 'web3'} );


Upd:

Explanation of comments:
The solution.... recursive function
const data = {
 user: 'ubuntu',
 hosts: {
 0: {
 name: 'web1',
},
 1: {
 name: 'web2',
 null: 3,
},
},
};

// classically on the if
function getIn(obj, parr) {
 if(typeof(obj[parr[0]]) == "undefined") {
 return null;
 } else {
 if(typeof(obj[parr[0]]) == "object") {
 if(parr.length > 1) {
 return getIn(obj[parr[0]], parr.slice(1))
 } else {
 return obj[parr[0]]
}
 } else {
 return obj[parr[0]];
}
}
}


// foolproof (when incorrect parameters) + switch case
function getIn(obj, parr) {
 if (
 typeof(obj) != "object" ||
 typeof(parr) != "object" ||
 parr.length == "undefined" ||
 parr.length == 0
 ) return null;
 switch (typeof(obj[parr[0]])) {
 case "undefined":
 return null;
 case "object":
 return (parr.length > 1)? getIn(obj[parr[0]], parr.slice(1)):obj[parr[0]]
default:
 return obj[parr[0]];
}
}

// even shorter 
function getIn(obj, parr){
 return !(
 typeof(obj) != "object" ||
 typeof(parr) != "object" ||
 parr.length == "undefined" ||
 parr.length == 0
)?
 typeof(obj[parr[0]]) == "object" ?
 (parr.length > 1)?
 getIn(obj[parr[0]], parr.slice(1)):obj[parr[0]] :
 obj[parr[0]] ?
 obj[parr[0]]: null:
null
}

// and pointer function
const getIn = (obj, parr) => !(
 typeof(obj) != "object" ||
 typeof(parr) != "object" ||
 parr.length == "undefined" ||
 parr.length == 0
)?
 typeof(obj[parr[0]]) == "object" ?
 (parr.length > 1)? getIn(obj[parr[0]], parr.slice(1)):obj[parr[0]] :
 obj[parr[0]] ? obj[parr[0]]:null :
 null;


UPD2:

A solution without recursive call
function getIn(obj, parr) {
 let o = obj;
 for(let i=0; i< parr.length; i++) {
 o = o[parr[i]];
 if(typeof(o)=="undefined") return null;
}
 return o;
}
Here is the assignment:
Implement the function getIn, which extracts from the object (which can be any depth) value by specified keys. Arguments:

The source object
An array of the keys used in the search value
In the case where access to the values is not possible, null is returned.

Examples
const data = {
 user: 'ubuntu',
 hosts: {
 0: {
 name: 'web1',
},
 1: {
 name: 'web2',
 null: 3,
},
},
};

getIn(data ['undefined']); // null
getIn(data, ['user']); // 'ubuntu'
getIn(data, ['user', 'ubuntu']); // null
getIn(data ['hosts', 1, 'name']); // 'web2'
getIn(data ['hosts', 0]); // { name: 'web1' }
getIn(data ['hosts', 1, null]); // 3
- charlene_Zie commented on April 3rd 20 at 18:33
@charlene_Zie, see response type is determined by the typeof()
Forward ;)

or am I ready to write the function? - toby.Stracke commented on April 3rd 20 at 18:36
@charlene_Ziehow to iterate over object keys wrote in the answer above. - toby.Stracke commented on April 3rd 20 at 18:39
@toby.Stracke, that's what I want to do!
Imagine that the function is called with parameters getIn(data ['hosts', 1, 'name'])
I want to walk through the array (second parameter) cycle and
1) If the first object is an object(in this case hosts)
{
then, to get to its properties, we write the chain of data(and add .host)
}otherwise, if this is a common property, the entry appears as follows: date['property'] - charlene_Zie commented on April 3rd 20 at 18:42
@charlene_Zie, This is not the case.
know what is recursive function?
getIn written as a recursive function and calls itself.

ie when you go to see funzio
is there anything in retrieved object from the first parameter is a property of the first element of the array the second parameter, if none then return null immediately
if so, then check a property of an object?
if not then return the value of the property
if Yes!? I call getIn again! and pass it the value of this property And an array of values of the second parameter starting with the 1st element

something like that. - toby.Stracke commented on April 3rd 20 at 18:45
@charlene_Zie, updated answer... - toby.Stracke commented on April 3rd 20 at 18:48
@toby.Stracke, the Course is not about recursion, but about the objects - charlene_Zie commented on April 3rd 20 at 18:51
@toby.Stracke, Look! I want on each iteration to check(the array is the second parameter) which element of the object in front of me. If the object property is object, then I put a certain design:
The first parameter - data
The second parameter, an element of the array .object
When connecting(all these constructs, you can write to a variable, which we return at the end), should form a chain - data.object(by the Way, another question, how to combine it all to make it all come out? )
->
Further, imagine that in the next iteration it the property of this nested object. Then design, added to recording data.object[object]
My question is, is that I don't know
1) How to check in a loop that I have, a property-object or just a property
2) How to connect all this? - charlene_Zie commented on April 3rd 20 at 18:54
@charlene_Zie, I have you on both questions already answered!
read carefully.
and even the solution provided.

The course is not about recursion, but about the objects


1. forbidden to solve using recursion??
2. you don't know recursive functions??
3. anything that the function object is passed and is passed on in a recursion?? i.e. this is the iteration of unknown depth.
4. you Pointed out how to solve it?? - toby.Stracke commented on April 3rd 20 at 18:57
@toby.Stracke,

1. forbidden to solve using recursion??
2. you don't know recursive functions??

You asked - I answered! Thought you would understand it...

3. anything that the function object is passed and is passed on in a recursion?? i.e. this is the iteration of unknown depth.

The object is then not transmitted, you are mistaken. Please re-read the job and my previous post.
In an hour I will be able to test what you wrote to me! - charlene_Zie commented on April 3rd 20 at 19:00
@charlene_Zie,
You asked - I answered! Thought you would understand it...

In fact, You once again did NOT answer, but who cares in principle then? well, okay... )
what YOU want on each iteration ... parampampam, understood it, but you never this iteration won't even try to describe! as you see it??
I just gave You the solution which can be at any level of nesting/depth, because "it bypasses itself" - recursion

Please re-read the job and my previous post.

really read....

The object is then not transmitted, you are mistaken.

I wrote about iteration recursion actually... just read the function code of the first or second and then it will be clear and/or my third comment. - toby.Stracke commented on April 3rd 20 at 19:03
@charlene_Zieadded a solution without recursive calls/bypass - toby.Stracke commented on April 3rd 20 at 19:06
@toby.Stracke, Your solution really works. I assumed that must be addressed in a task. But your solution opened my gap in knowledge of how an object works in the cycle when assigning a value. I had some confusion, so please help me to understand.
The fact that I was confused by the line:
o = o[parr[i]];
With the passage of the cycle, instead i substituted a number from 0 to the length of the element array, which extends corresponding to that index value. That is, in turn, substitutes (if we're talking about this call: getIn(data ['hosts', 1, null]);)
1) o['hosts'];
2) o[1];
3) o[null];

I assumed so happens that the next iteration of the fray the previous value of o.
I understand that after completion of the cycle, the variable(object) o as follows:
data['hosts'][1][null]
- correct me if I'm wrong! That's not clear. Please explain! - charlene_Zie commented on April 3rd 20 at 19:09
@charlene_Zieactually not variables store objects and object references.
and here...
o = o[parr[i]];
in the loop is OVERWRITTEN variable on on o["key"]
and if, before the rst iteration of the o was data
after the rst iteration of the o will be data["key"]
and... if you do not leave on the condition that the result is undefined, i.e. there is no such property/key in the object.
then, in the second iteration in o record again o["Key2"], and because in the first iteration in o is already data["key"], in fact, written data["key"]["Key2"]
etc.
ie o link to the current nesting level.
and if not undefined and the loop parr (list keys) is not over, it continues
thus at the end of the cycle o will contain last element from the list and return it.
if some point o is undefined, respectively, then the key is not found and null is returned

in principle, it is also a kind of recursion.... o = o[parr[i]] - toby.Stracke commented on April 3rd 20 at 19:12
And one more thing wanted to ask. There is a ready code.
const data = {
 user: 'ubuntu',
 cores: 4,
 os: 'linux',
};

function pick(obj, arr){
 let result = [];
 let all = Object.entries(obj);
 for([key, value] of all){
 for(let i = 0; i < arr.length; i += 1){
 if(key == arr[i]){
 result.push(`${key}: ${value}`);
}
}

}
 return result;
}

pick(data, ['user']); // { user: 'ubuntu' }
console.log(pick(data, ['user', 'os'])); // { user: 'ubuntu', os: 'linux' }
pick(data, []); // {}
pick(data, ['none']); // {}

The only problem is that I can return an array(result). But I need to return an item. Can't understand how to do it... - charlene_Zie commented on April 3rd 20 at 19:15
@charlene_Zie, well, I already gave a link to how to add elements in the object...
bologer.ru/javascript-kak-dobavit-novyj-element-v-obekt

function pick(obj, arr){
 let result = {};
 let all = Object.entries(obj);
 for([key, value] of all){
 for(let i = 0; i < arr.length; i += 1){
 if(key == arr[i]){
 result[key]= value;
}
}

}
 return result;
}


you can still make a string and use JSON.parse()
type this:
JSON.parse('{"user":"ubuntu","os":"linux"}') - toby.Stracke commented on April 3rd 20 at 19:18
@toby.Stracke, result[key]= value;
- does not work! - charlene_Zie commented on April 3rd 20 at 19:21
@charlene_Zie, strange...
https://jsfiddle.net/w70d9hrf/
all the rules. - toby.Stracke commented on April 3rd 20 at 19:24
@charlene_Zie, you watch my review??
line:
let result = {}; - toby.Stracke commented on April 3rd 20 at 19:27
@charlene_Zie, read the article?
there too - obj = {}; // Make an object empty again - toby.Stracke commented on April 3rd 20 at 19:30
April 3rd 20 at 18:32
Do not use typeof arrays are also objects she considered to be
console.log(typeof([]))
//Object
console.log(Object.prototype.toString.call( { } ).indexOf('object Object') ==1)
//true
console.log(Object.prototype.toString.call( [ ] ).indexOf('object Object') ==1)
//False

Function isObject:
const isObject = objRef => Object.prototype.toString.call( objRef ).indexOf('object Object') == 1
in this context, oject or array doesn't matter in principle, IMHO. - toby.Stracke commented on April 3rd 20 at 18:35
@toby.Stracke, did not even see the code to be honest, I saw that everything in typeof wrote - Savanah.Moen12 commented on April 3rd 20 at 18:38

Find more questions by tags JavaScript