var v1 = new class(params) , object = {} - node.js

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"

Related

Convert Specific String to JSON Object

const test ="[{contactId=2525, additionDetail=samle}]";
I need to convert this string to a JSON object. It will dynamically load like this string. I need to particular string to convert to a JSON object.
JSON.parse(test) command not working for this. I attached the error here.
For that specific string, you'd have to parse it yourself.
const test = '[{contactId=2525, additionDetail=samle}]';
const obj = {};
test.split(/[{}]/)[1].split(/, /).forEach((elm) => {
const entry = elm.split('=');
obj[entry[0]] = entry[1];
});
What I am doing is splitting the string on the braces and selecting the second element (utilising regex) then splitting that on comma and space (again regex) then loop over the result and assign to an object.
You can then JSON.stringify(obj) for the result.
:edit:
For the second string you've asked for there is another, potentially more refined, answer. You'll need to first replace the = with : (I've again used a regex), then you use a regex to match the words and sentence and use a function to add the quotes.
const test = '[{contactId=2525, additionDetail=samle}]';
const test2 = "[{contactId=2525, additionDetail=rrr additional Detail, medicationType={medicationTypeId=3333, medicationType=Tablet}, endDate=2022-12-30}]";
const replaced = test.replace(/=/g,':')
const replaced2 = test2.replace(/=/g, ':');
const replacer = function(match){
return '"' + match + '"';
}
const replacedQuote = replaced.replace(/(?!\s)[-?\w ?]+/g,replacer);
const replaced2Quote = replaced2.replace(/(?!\s)[-?\w ?]+/g,replacer);
const obj = JSON.parse(replacedQuote);
const obj2 = JSON.parse(replaced2Quote);
You should note that Json means javascript object notation, so you need to create a JavaScript object to get started:
const test ="[{contactId=2525, additionDetail=samle}]";
let obj = Object.create(null)
You can now define your variable as one of the object properties :
obj.test = test
Now we have a JavaScript object and we can convert it to json:
let convertedToJson = JSON.stringify(test);
[{contactId=2525, additionDetail=samle}]
this is not a valid JSON-string, and it cannot be parsed by JSON.parse()
the correct JSON-string would be:
const test ='[{"contactId":2525, "additionDetail":"samle"}]';

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 instantiate a object with a variable key-value pair in Javascript?

I want to instantiate a object with its key being a variable. Something along the lines of this:
var deleteDuplicates = function(head) {
let dict = {
`${head.val}`: 1
}
}
Is something like this possible besides having another line write to it:
let dict = {}
if (head) dict[head.val] = 1
The syntax for throwing a variable in as a key is:
let dict = {
[head.val]: 1
}
Source: ES6

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];
});

Resources