Why is the 'book1 ' printed? - javascript

function defineReactive(data, key, val) {
observe(val); // 递归遍历所有子属性
console.log(key,val);
}
function observe(data) {
Object.keys(data).forEach(function(key) {
console.log(data,key,data[key])
defineReactive(data, key, data[key]);
});
};
var library = {
book1: {
name: ''
}
};
observe(library);
The above is the code part, and the screenshot below is running. Why does 'book1' print?

You are getting keys in library object in this line Object.keys(data).
the keys in library? it is book1. Unless you want to find keys inside book1 you need to do Object.keys for nested object.
TL.DR: Object.keys(obj) only find keys in the first level.

Related

Find Name of Array obj from Json

Here I want to read key name of obj.
Like "CIRTGroupBox1", "CIRTGroupBox2"
Try this :
var arr = [{
'CIRTGroupBox1': ''
}, {
'CIRTGroupBox2': ''
}, {
'CIRTGroupBox3': ''
}];
// Using array.map() method
var usingMapKeys = arr.map((obj) => Object.keys(obj)[0]);
// Using Object.entries() method
var usingEnteriesKeys = arr.map((obj) => Object.entries(obj)[0][0]);
console.log(usingMapKeys);
console.log(usingEnteriesKeys);
is it?
var x = {
"ob1": "value",
"ob2": {
"ob21": "value"
}
};
var keys = Object.keys(x);
console.log(keys);
You can do that using Object.keys method in JS like below
var keys = Object.keys(groupBoxesTemp);
This will return string array and each item in it is the key of this object.
If you want to read values pertaining those 2 keys, you can do like below using the for-in loop:
for(item in groupBoxesTemp){
console.log('key is: ', item);
console.log('value is: ', groupBoxesTemp[item]);
}
Based on your screenshot, temp is an array of objects which has 3 objects in it. You can do that too like below:
temp.forEach(function(item, index){
//key for all objects in the array will be logged.
console.log( Object.keys(item) );
});

Extracting properties from array

I have this function which takes a json parameter which contains an array of search objects.
function receiveSearch(search, json) {
return {
type: RECEIVE_SCHOOL_SEARCH,
items: json.packages,
receivedAt: Date.now(),
search: Object.assign({}, search, { next: json.next, start: search.next }),
};
}
My json
property looks like:
>0:Object
>1:Object
>2:Object
>3:Object
...{ more }
I would like to return to the search object two properties from json i.e name and suburb. How do I do this? I would prefer to use something neat like lodash/ramda/underscore but plain js is fine.
And each object contains the following properties:
id:"10360"
centreId:776
name:"ABBOTSFORD"
suburb:"TARNEIT"
The easiest solution to you problem using JavaScript could be make a new object which contains only required property and return that.
Just assume your json looks like this:
var x = {search:{id:"10360",centreId:776,name:"ABBOTSFORD",suburb:"TARNEIT"},otherProp:val}
To get required properties, you can make another function and return the object with required fields:
function ReturnRequiredPropertyObject(anyObj)
{
var newObj = {};
newObj.search = {};
newObj.search.name = anyObj.search.name;
newObj.search.suburb = anyObj.search.suburb;
return newObj;
}
You can put the above code in loop if you are getting an array of search object.
To make the above code generic, we can do the following:
function ReturnRequiredPropertyObject(anyObj,requiredPropertyArray)
{
var newObj = {};
for(var counter = 0;counter<requiredPropertyArray.length;counter++)
{
newObj[requiredPropertyArray[counter]] = anyObj[requiredPropertyArray[counter]];
}
return newObj;
}
Hope this will help.
Ok resolved.
Answer is
_.map(json,_.partialRight(_.pick,['name','suburb']));

How to iterate through nested JSON values using asnyc.js

I'm relatively new to nodeJS/Javascript's asynchronous nature (Python background) and trying am trying to figure how to step through a nested JSON object, extract it's values using asnyc.js.
I came across this snippet, How to navigate in nested JSON.
function recursiveGetProperty(obj, lookup, callback) {
for (property in obj) {
if (property == lookup) {
callback(obj[property]);
} else if (obj[property] instanceof Object) {
recursiveGetProperty(obj[property], lookup, callback);
}
}
}
Which works great with this sample object, foo.
var foo = {
'key_1' : 'val1',
'key_2': {
'key_3': 'val3',
'key_4': 'val4'
}
}
recursiveGetProperty(foo, 'key_1', function(obj) {
console.log(obj);
});
returns 'val1'
recursiveGetProperty(foo, 'key_3', function(obj) {
console.log(obj);
});
returns 'val3'
This is exactly what I needed but when I feed it key values via iteration:
var keys = ['val1', 'val3'];
for (var keys in keys) {
recursiveGetProperty(foo, keys, function(obj) {
console.log(obj);
});
}
nothing is logged to console. so I wrote a logging function:
function log(obj) {
console.log(obj);
}
and tried:
for (var key in keys) {
recursiveGetProperty(foo, keys, log(obj));
}
but i get ReferenceError: obj is not defined.
I was told it's not a great idea to execute a callback inside a for loop, I'm not exactly sure why so I looked into async.js. It seems like the right solution for what I want but I have no idea how to go about it.
Using async.js, I would like to build a series of recursiveGetProperty functions, store them in an array, and then execute those calls asynchronously but I'm stumped on how to approach the problem.
What I would ultimately want is something like this:
async.each(['key_1', 'key_2', 'key_3'], recursiveGet(key) {
doSomethingWithData();
}, function(err) {
doSomethingWhenDone();
});
This would be used on an ExpressJS server to parse JSON and do something with it afterwards.
Any help or suggestion would be greatly appreciated.
There are bug in this code
var keys = ['val1', 'val3'];
for (var keys in keys) {
recursiveGetProperty(foo, keys, function(obj) {
console.log(obj);
});
}
The array of keys (line 1) is overwritten by the keys index (line 2) of the for loop. So let's rename that key.
For an iterated array a key would be a number (0, 1, ..., n), not a string. You need to use those numbers as indices to keys
Also your recursiveGetProperty finds by keys not values.
So the code should be
var keys = ['key_1', 'key_2'];
for (var key in keys) {
recursiveGetProperty(foo, keys[key], function(obj) {
console.log(obj);
});
}
var keys = ['key_1', 'key_2'];
keys.forEach(function (key) {
recursiveGetProperty(foo, key, function(obj) {
console.log(obj);
});
});
http://jsfiddle.net/fPRQK/
Issues in your code:
for(var key in obj) works with object properties only, not with array values. Use Array.forEach or a regular for loop instead.
recursiveGetProperty(foo, keys, log(obj)): This would call log instantly and pass it's return value to recursiveGetProperty. You could either pass just log or function (obj) { log(obj); }, which in this case mean the same. Also in this case what you want to pass is key.

How to convert hash in to an array?

$VAR1 = {
'time_stamp' => '06/20/13 09:53',
'data' => {
'TOS1' => {
'69' => {
'65' => {
'LINK_STATUS' => 1,
'KPIS' => {
Aailability' => {
'status' => 'G',
'val' => '100'
},
'Completion Time' => {
'status' => 'G',
'val' => '1'
}
}
}
}
}
}
};
I want to convert this hash in to an array. i got this in json and store it in one variable in javascript. i want display this all values in tabular format
plz suggest me
So what you have there is a deeply-nested object graph. To make an array out of it, you'd probably use for-in to loop through the properties of the object at each level and use the values to build up an array. It's not remotely clear from the question what you might want that array to look like, so I can't really help further.
Here's what a for-in loop looks like:
var key;
for (key in obj) {
// Here, `key` will have each property name; to get
// that property's value, use obj[key]
}
So for example:
var obj = {
a: 1,
b: 2
};
var key;
for (key in obj) {
console.log(key + "=" + obj[key]);
}
...will output
a=1
b=2
(the order isn't guaranteed).
I don't see any reason to convert that to an array. In Javascript arrays can only have numerical keys.
You can iterate over the object properties with a for in:
for (var property in $VAR1) {
if ($VAR1.hasOwnProperty(property)) {
console.log(property); // time_stamp
console.log($VAR1[property]); // 06/20/13 09:53
}
}
Given that you have nested objects, you'd need nested loops to iterate over the nested objects.

Accessing elements of JSON object without knowing the key names

Here's my json:
{"d":{"key1":"value1",
"key2":"value2"}}
Is there any way of accessing the keys and values (in javascript) in this array without knowing what the keys are?
The reason my json is structured like this is that the webmethod that I'm calling via jquery is returning a dictionary. If it's impossible to work with the above, what do I need to change about the way I'm returning the data?
Here's an outline of my webmethod:
<WebMethod()> _
Public Function Foo(ByVal Input As String) As Dictionary(Of String, String)
Dim Results As New Dictionary(Of String, String)
'code that does stuff
Results.Add(key,value)
Return Results
End Function
You can use the for..in construct to iterate through arbitrary properties of your object:
for (var key in obj.d) {
console.log("Key: " + key);
console.log("Value: " + obj.d[key]);
}
Is this what you're looking for?
var data;
for (var key in data) {
var value = data[key];
alert(key + ", " + value);
}
{
"d":{
"key1":"value1",
"key2":"value2"
}
}
To access first key write:
let firstKey=Object.keys(d)[0];
To access value of first key write:
let firstValue= d[firstKey];
By using word "b", You are still using key name.
var info = {
"fname": "Bhaumik",
"lname": "Mehta",
"Age": "34",
"favcolor": {"color1":"Gray", "color2":"Black", "color3":"Blue"}
};
Look at the below snippet.
for(key in info) {
var infoJSON = info[key];
console.log(infoJSON);
}
Result would be,
Bhaumik
Mehta
Object {color1: "Gray", color2: "Black", color3: "Blue"}
Don’t want that last line to show up? Try following code:
for(key in info) {
var infoJSON = info[key];
if(typeof infoJSON !== "object"){
console.log(infoJSON);
}
}
This will eliminate Object {color1: “Gray”, color2: “Black”, color3: “Blue”} from showing up in the console.
Now we need to iterate through the variable infoJSON to get array value. Look at the following whole peace of code.
for(key in info) {
var infoJSON = info[key];
if (typeof infoJSON !== "object"){
console.log(infoJSON);
}
}
for(key1 in infoJSON) {
if (infoJSON.hasOwnProperty(key1)) {
if(infoJSON[key1] instanceof Array) {
for(var i=0;i<infoJSON[key1].length;i++) {
console.log(infoJSON[key1][i]);
}
} else {console.log(infoJSON[key1]);}
}
}
And now we got the result as
Bhaumik
Mehta
Gray
Black
Blue
If we use key name or id then it’s very easy to get the values from the JSON object but here we are getting our values without using key name or id.
Use for loop to achieve the same.
var dlist = { country: [ 'ENGLAND' ], name: [ 'CROSBY' ] }
for(var key in dlist){
var keyjson = dlist[key];
console.log(keyjson)
}

Categories