Getting object attribute value from URL - node.js

So I get some data from a websites API. I get it in the following way:
function httpGet(url){
var response = requestSync(
'GET',
url
);
return response.body;
}
const listValue = JSON.parse(httpGet("URL"));
The gathered data basically looks like this:
listValue = {
banana: "yellow",
apple: "green",
kiwi: "brown"
}
I also have another object that looks like this:
object = {
'yellow': 11,
'green': 5,
'brown': 14,
}
My goal is to access the the data in object object via listValue attribute like so:
var color = listValue.banana;
var value = object.color;
But the color variable always ends up being undefined no matter what I do. I've tried stringifying the color variable and all sorts of things but havent figured out what's the problem. If you have a clue please let me know.

Try accessing the object like this:
var color = listValue.banana;
var value = object[color];

May be you can access it via ?
var color = listValue.banana;
var value = object[color];
Be sure to check if the key exists before accessing it. (Object.prototype.hasOwnProperty.call(pbj, key))

Related

How do I access content from JSON string?

I am receiving a JSON object from the backend now I just want "result" array only in my template variable in my angular application from it.
{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}
Try with
variable_name["result"].
Try with
var data = response from the backend
var result = data.result;
$var = '{"result":[{"name":"Sunil Sahu","mobile":"1234567890","email":"abc#gmail.com","location":"Mumbai","Age":"19"}],"stats":200}';
If your $var is string, you need to turn it to "array" or "object" by json_decode() function
object:
$var_object = json_decode($var); //this will get an object
$result = $var_object->result; //$result is what you want to get
array:
$var_array = json_decode($var, true); //this will get an array
$result = $var_array['result']; //$result is what you want to get
Else if $var is object, direct use
$result = $var->result; //$result is what you want to get
As result is an array of objects, you can either use any loop to extract key value pair or you can directly access the array using index value.
var results = data["result"] // this would return an array
angular.forEach(results, function(value, key) {
//access key value pair
});
For accessing results in HTML, ng-repeat directive can be used.
Your question didn't explain further, but in the simple way try this :
const stringJson = `{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}`
const obJson = JSON.parse(stringJson);
console.log(obJson.result);

Adding data to JSON object with data from variables

So my goal is to have an object variable that will be empty at the start but as the code starts running it would get filled up with data from other varibales. When it gets filled up it should look like this:
var fruits = [banana, apple, ...];
var colors = [yellow, green, ...];
var calories = [300, 250, ...]
//the JSON object
{
banana :
{
"color" : "yellow",
"calories" : 300
},
apple :
{
"color" : "green",
"calories" : 250
},
...
}
As you can see all of the data is supposed to be pulled from other variables and this is where I bump into problems. I've tried the following:
var object.fruits[0] = {colors : calories};
//also tried this
var object.fruits[0] = "{""'" + (colors[0]) + "'":+calories[0]+"}";
//and tried many other things...
I've been failing to counter this for at least an hour now and what makes it worse is that some data is supposed to come from other JSON objects. Any idea how to make it work? Also note that having them in an object array is not a option as the list will be HUGE and therefore the time efficiency will be very poor.
Maybe try something like this
res = {}
fruits.map((key, index) => {
res[key] = {
'color': colors[index],
'calories': calories[index]
}
})
You can do like this but yeah put validations to make sure all three arrays are of equal length.
Whenever you want to add a property to an Object where the property value is a value of another variable it is better to use the bracket notation to add the properties to the object [] as used below.
One more thing better use let and const in place of var.
Finally you can use JSON.stringify() to convert into JSON String from the Javascript Object.
'use strict';
const fruits = ['banana', 'apple'];
const colors = ['yellow', 'green'];
const calories = [300, 250];
const fruits_object = {};
for (let i = 0; i < fruits.length; i++) {
fruits_object[fruits[i]] = {};
fruits_object[fruits[i]]['color'] = colors[i];
fruits_object[fruits[i]]['calories'] = calories[i];
}
console.log(JSON.stringify(fruits_object));
Just do it normally like so:
color: colors[0]
and then call JSON.stringify on the entire object like so
JSON.stringify({color: colors[0]})

Find JSON value using variable from function

I'm working on a function where I need to be able to input a string which is a key in a JSON object then I need to be able to take the actual object and tack on the string to get the correct value from the JSON
function contact(contact_method) {
let method = array[place].settings.contact_method; // Example for contact_method is 'first_contact_method'
console.log(method)
}
The idea is I have 3 different contact methods and I'd like to be able to use the same function for all 3. I know the code above is barely a function but I think it shows what I want to be able to do.
I could not find anything on MDN or SO about this. I had tried using ES6 and string with `` but that did not work it just returned [object Object].first_contact_method
You can access keys of objects with a variable by using [].
For instance:
const obj = { a: 4, b: 5, c: () => { /* do something*/}, d() { /* do something*/ } }
const keyA = 'a'
const keyC = 'c'
const valueA = obj[keyA] // valueA === 4
const methodC = obj[keyC]
// Call method c
methodC()
// or short
obj[keyC]()
// and even for "real" methods
obj['d']()

How to use dot(.) to MongoDB(Mongoose) schema as a parameter [duplicate]

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

var v1 = new class(params) , object = {}

Hi I don't know what exactly do this kind of sentences:
var v1 = new class(params) , object = {}
The real example was: (From https://github.com/visionmedia/parted Usage paragraph)
var parser = new multipart(type, options) , parts = {};
I understand that parser will be a new multipart object, but parts?! what exactly do? Create empty object? where I have to push some data?
Thank's in advice!
var declarations can take multiple variables. Example:
var a = 1, b = 2;
That declares two variables, a and b, and assigns them the values 1 and 2, respectively.
In other words, in your example, parts is a new variable that is assigned an "empty" object.
{} in javascript creates a new empty object using JavaScript's literal object notation.
Other examples of creating objects using the literal object notation:
obj1 = { foo: 2 } // Now obj1.foo is 2
obj2 = { foo: 3, bar: "hello" } // Now obj2.foo is 3 and obj2.bar is "hello"

Resources