Apply filter to JSON.parse() dynamically - javascript

I have the following js:
var text = '{"firstName" : "abc", "lastName" : "def", "age" : 25}';
obj = JSON.parse(text).firstName;
console.log(obj);
This prints the value corresponding to the key firstName as expected. However what I am trying to do is, I want to store the key to be fetched in a variable and use it along with JSON.parse() statement. Something like this:
var text = '{"firstName" : "abc", "lastName" : "def", "age" : 25}';
var filter = 'firstName';
obj = JSON.parse(text).filter;
console.log(filter)
console.log(obj);
This code prints 'undefined' onto the console. What am i doing wrong?

Change:
obj = JSON.parse(text).filter;
to
obj = JSON.parse(text)[filter];
There are two ways to access properties: dot notation and bracket notation.
var test = object.property; //(dot notation)
var test = object[property_name]; //(bracket notation)
The issue you are facing is that you are trying to access a property called 'filter' on your object which does not exists and therefore undefined.

When trying to access a value with a key stored in a variable, you need to use the square brackets notation.
obj.key is equivalent to obj['key'], but var x = 'key'; obj.x is not equal to obj.key.
Open your console and run this code snippet
var text = '{"firstName" : "abc", "lastName" : "def", "age" : 25}';
var filter = 'firstName';
obj = JSON.parse(text)[filter];
console.log(filter);
console.log(obj);
A simple example
var obj = { a: 'A' },
filter = 'a';
console.log( obj.a ); // outputs 'A'
console.log( obj['a'] ); // outputs 'A'
console.log( obj[filter] ); // outputs 'A'
console.log( obj.filter ); // outputs undefined, obj does not have a 'filter' property

this is trying to access an attribute called filter from the parsed JSON which doesn't exist and is therefore undefined.
Instead you want JSON.parse(text)[filter]

Related

Why does error occur at var obj={'A':'B','C':obj['A']};?

I want to create an javascript object, which value of "C" copies value of "A" :
var obj={
'A':'some complex function returns a string',
'C':obj['A']
};
But it has errors. I try to check if key 'A' really created:
var f=function(str){
console.log(str);
return str;
};
var obj={
[f('A')]:[f('B')],
"C":obj['A']
};
which prints
B
A
and then errors. Which means 'A' created but it still says obj['A'] is not defined. Why would that happen?
Your current attempt obviously fails because by the time the code constructs new object the value of obj variable was not assigned yet.
You could check it by using
var obj = { C: typeof obj}
I want to create an javascript object, which value of "C" copies value of "A"
If you want C to always reflect the value of A you could use
var obj = {
A: 'Some value',
get C() {
return this.A;
}
}
Or split obj declaration
var obj = { A: 'Some Value' };
obj.C = obj.A
You get the error because obj was not yet defined when you attempted to acces it from inside of it.
To make your code work you could use a getter.
The get syntax binds an object property to a function that will be
called when that property is looked up. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
Also you do not need quotes for your object properties.
Quotes can be omitted if the property name is a numeric literal
or a valid identifier name.
var obj = {
A : 'Hello',
get C() {
return this.A;
}
};
console.log(obj.C);
You can not reference a variable that has not created yet. You can do it like this.
var obj = { 'A' : 'some complex function returns a string' }
obj['C'] = obj['A']

JavaScript - Pushing JSON Object Using Value as Element Name

I'm trying to push an object inside an array with dynamic attribute name.
Let's say we have the following variables defined
myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };
attribName = "name";
myValue = "myValue";
parsedJSON = JSON.parse(myJSON);
parsedJSON["students"].push({attribName : myValue});
myJSON = JSON.stringfy(parsedJSON);
The example isn't working. Is there a way to push an object with dynamic attribute name?
From MDN,
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
Also note that input you has provided is object, not json
var myJSON = {
"students": [{
"name": "Your Name"
}, {
"name": "My Name"
}]
};
var attribName = "name";
var myValue = "myValue";
var obj = {};
obj[attribName] = myValue;
myJSON["students"].push(obj);
console.log(myJSON);
function(key, value, json) {
var obj = {};
obj[key] = value;
json['students'].push(obj);
return arr;
}
You can also do the modification in your code :
myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };
attribName = "name";
myValue = "myValue123";
myJSON["students"].push({attribName: myValue});
console.log(myJSON);

JS how to determine if key exists in JSON KVP structure?

For JSON structured like so :
descriptors = {"key1" : { "propertyA": "propertyA-value1",
"propertyB": "propertyB-value1" },
"key2" : { "propertyA": "propertyA-value2",
"propertyB": "propertyB-value2" }}
How to determine if a given key exists ?
# argKey is function arg supplied by caller
descriptor = descriptors[argKey]
if descriptor != undefined
# do something with descriptor
Is that right ?
Your code is not valid - you have [ ] brackets, which delimit an array, but you appear to be trying to put an object inside. You need this instead.
descriptors = {"key1" : { "propertyA": "propertyA-value1",
"propertyB": "propertyB-value1" },
"key2" : { "propertyA": "propertyA-value2",
"propertyB": "propertyB-value2" }};
That aside, to test for the presence of a property you can use the in operator.
'key1' in descriptors;
>> true
Since the test key is just a string, you can store it in a variable if it is not known ahead of time.
var keyName = 'key1';
if (keyName in descriptors) {
// do something
}
Per your question in the comments, to access the value of the property, you can say
descriptors[keyName];
// More deeply nested example
var keyName = 'key1';
var propName = 'propertyA';
console.log(descriptors[keyName][propName]);
That's not a valid JavaScript object. If you want to test the existence of a property on an object, use:
Object.prototype.hasOwnProperty
If the property exists and has value of undefined your solution won't work. Check it with typeof or hasOwnProperty instead:
var obj = {
prop: undefined
};
console.log(obj.prop === undefined); // true
console.log(typeof obj.prop === undefined); // false
console.log(!obj.hasOwnProperty("prop")); // false

How to get value in an object's key using a variable referencing that key?

I have an object and I can reference key a as in the following:
var obj = {
a: "A",
b: "B",
c: "C"
}
console.log(obj.a); // return string : A
I want to get the value by using a variable to reference the object key as below:
var name = "a";
console.log(obj.name) // this prints undefined, but I want it to print "A"
How can I do this?
Use [] notation for string representations of properties:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
obj["a"] is equivalent to obj.a
so use obj[name] you get "A"
Use this syntax:
obj[name]
Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).
obj["Hey, this is ... neat?"] = 42
You can get value of key like these ways...
var obj = {
a: "A",
b: "B",
c: "C"
};
console.log(obj.a);
console.log(obj['a']);
name = "a";
console.log(obj[name])
I use the following syntax:
objTest = {"error": true, "message": "test message"};
get error:
var name = "error"
console.log(objTest[name]);
get message:
name = "message"
console.log(objTest[name]);
productList = {
"name": "Title"
}
var key = "name";
console.log(productList[key])
productList is an arbitraty object with only one key. the key variable holds the same key as a string.
Using the [] you can access the value dynamically.
https://jsfiddle.net/sudheernunna/tug98nfm/1/
var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
if(days[value]){
usertrue++;
}else{
userfalse++;
}
console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);
var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);
for (i=0; i<x.length; i++) {
console.log(o[x[i]]);
}
IAB
fyi, if the type of the object is not known it's a little trickier:
var name = "a";
console.log(obj[name as keyof typeof obj]);
(refer to this post)

How to convert string as object's field name in javascript

I have a js object like:
obj = {
name: 'js',
age: 20
};
now i want to access name field of obj, but i can only get string 'name', so how to convert 'name' to obj's field name, then to get result like obj.name.
Thank you in advance.
You can access the properties of javascript object using the index i.e.
var obj = {
name: 'js',
age: 20
};
var isSame = (obj["name"] == obj.name)
alert(isSame);
var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
isSame = (obj[nameIndex] == obj.name)
Check example# : http://www.jsfiddle.net/W8EAr/
In Javascript, obj.name is equivalent to obj['name'], which adds the necessary indirection.
In your example:
var fieldName = 'name'
var obj = {
name: 'js',
age: 20
};
var value = obj[fieldName]; // 'js'
Not related at all, but for anyone trying to define object's field name from a string variable, you could try with:
const field = 'asdf'
const obj = {[field]: 123}
document.body.innerHTML = obj.asdf
It's quite simple, to access an object's value via a variable, you use square brackets:
var property = 'name';
var obj = {name: 'js'};
alert(obj[property]); // pops 'js'
As objects are associative arrays in javascript you can access the 'name' field as obj['name'] or obj[fieldName] where fieldName = 'name'.

Categories

Resources