Adding data to JSON object with data from variables - node.js

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

Related

Merge two diffrent json in one json

I have two json arrays like
var json1 = [{"city":"Ahmedabad"}]
var json2 = [{"State":"Gujarat"}]
I want them merge in to single arrays
var finalObj = [{"city":"Ahmedabad","State":"Gujarat"}]
If you are using concat() method then the arrays will get merged not the elements then you will get an output somewhat like
[{"city":"Ahmedabad"},{"State":"Gujarat"}]
If you need an output like this,
[{"city":"Ahmedabad","State":"Gujarat"}]
then you can implement this,
var json1 = [{"city":"Ahmedabad"}];
var json2 = [{"State":"Gujarat"}];
function jsonConcat(destinationObj, sourceObj) {
for (var key in sourceObj) {
destinationObj[key] = sourceObj[key];
}
return destinationObj;
}
//since json1 & json2 are arrays you must mention index,
//here index is 0, because it's first json object
var finalObj = jsonConcat(json1[0], json2[0])
console.log(finalObj)
IMPORTANT - This function will replace if similar keys found in both arrays !
If two json arrays have the same length, like your example, each json object is a array what includes one object.
You can loop through each item of the json arrays, then merge all of them to a object, finally push it into a array - finalObj.
My way use Object Rest/Spread Properties, the feature available with es2018:
var json1 = [{ "city": "Ahmedabad" }]
var json2 = [{ "State": "Gujarat" }]
var finalObj = [];
for (let i = 0; i < json1.length; i++) {
finalObj.push({
...json1[i],
...json2[i]
})
}
console.log(finalObj);
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var finalObj = json1.concat(json2)
merge your array
use reduce to merge all the items into one object
wrap in array
var combinedObj = [...json1, ...json2].reduce((acc, obj) => {
return {
...acc,
...obj
}
}, {})
var combinedArr = [...combinedObj]
You can do merge by using spread / rest operators i.e ...
var json1 = [{"city":"Ahmedabad"}]
var json2 = [{"State":"Gujarat"}]
var result = [...json1, ...json2]; //this will merge them into one.
result will be new array as we have merge them into one.
You can also user concat method of Javascript. Please refer below for concat -
https://www.w3schools.com/jsref/jsref_concat_array.asp
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_concat

Getting object attribute value from URL

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))

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']()

Sharing & modifying a variable between multiple files node.js

main.js
var count = 1;
// psuedocode
// if (words typed begins with #add)
require('./add.js');
// if (words typed begins with #remove)
require('./remove.js');
// if (words typed begins with #total)
require('./total.js');
module.exports.count = count;
total.js
var count = require('./main.js').count;
console.log(count);
add.js
var count = require('./main.js').count;
count += 10;
console.log(count);
remove.js
var count = require('./main.js').count;
count -= 10;
console.log(count);
console.log
1
11
-9
Background:
I have an application (irc bot), and I want to add a feature that peeps can do #add 1 or #remove 1. I have a main.js that then requires different files depending on the triggers that are said. So add would trigger the add.js file, and that would then require('main.js') and add 10 (10 for simplification, it'll actually parse the number and use that number) to it. The problem I'm having is when someone goes about and does #remove. It require('main.js') and subtracts 10 from 1 resulting in -9. And doing #total would output 1.
I've done a fairly good search for module.exports and I haven't come across an example like the one i listed above. The docs don't include any examples close to what I'm wanting to do; and these questions 1, 2 I understand--but aren't of any usefulness to me--as I understand what's being said there.
Question:
I'd like to have both #add and #remove manipulate the same variable ( count ), and for #total to return the total of count with the #add and #removes taken into account. Am I using module.exports incorrectly; or is there a common way that variables are shared, with one file being able to modify the contents of the module.exports and returning the results to the main.js file?
Your problem is that when you do var count = require('./main.js').count;, you get a copy of that number, not a reference. Changing count does not change the "source".
However, you should have the files export functions. Requiring a file will only run it the first time, but after that it's cached and does not re-run. see docs
Suggestion #1:
// main.js
var count = 1;
var add = require('./add.js');
count = add(count);
// add.js
module.exports = function add(count) {
return count+10;
}
#2:
var count = 1;
var add = function() {
count += 10;
}
add();
#3: Personally i would create a counter module (this is a single instance, but you can easily make it a "class"):
// main.js
var counter = require('./counter.js');
counter.add();
console.log(counter.count);
// counter.js
var Counter = module.exports = {
count: 1,
add: function() {
Counter.count += 10;
},
remove: function() {
Counter.count += 10;
}
}
Not sure if this new or not but you can indeed share variables between files as such:
main.js
exports.main = {
facebook: null
};
counter.js
var jamie = require('./main');
console.info(jamie); //{facebook: null}
jamie.main.facebook = false;
console.info(jamie); //{facebook: false}
anothercheck.js
var jamie = require('./main');
console.info(jamie); //{facebook: null} //values aren't updated when importing from the same file.
jamie.main.facebook = true;
console.info(jamie); //{facebook: true}
Now you can share between files.
I know I'm a little bit late to answer this questions, just 7yrs!
You can simply use a global variable:
global.myVar = 'my-val';
console.log(myVar); // returns 'my-val'
// from here on it's accessable to all modules by just the variable name
using-global-variables-in-node-js
I have same problem like you,.. Sometimes I'd like to sharing variables between multiple files because I love modular style eg. separating controller, function, models in different folders/files on my node.js script so I can easy manage the code.
I don't know if this is the best solution but I hope will suit your needs.
models/data.js
// exports empty array
module.exports = [];
controllers/somecontroller.js
var myVar = require('../models/data');
myVar.push({name: 'Alex', age: 20});
console.log(myVar);
// [{ name: 'Alex', age: 20 }]
controllers/anotherController.js
var myVar = require('../models/data');
console.log(myVar);
// This array has value set from somecontroller.js before...
// [{ name: 'Alex', age: 20 }]
// Put new value to array
myVar.push({name: 'John', age: 17});
console.log(myVar);
// Value will be added to an array
// [{ name: 'Alex', age: 20 }, { name: 'John', age: 17}]
There is no way you can share a reference between different files. You shouldn't be.
I have a main.js that then requires different files depending on the triggers that are said
I don't think that's a good idea. All require statements you'll ever need must be at the top of the file.
I also see that You're requiring main.js in total.js and total.js in main.js. The require() function imports the module.exports of the file and assigns it to the namespace you provide. Your code shouldn't be split into files this way. You extract code into separate files only when they're modules by themselves. And if you do, you wouldn't be importing 2 files on each other.
It is also good to note that in javascript, when you assign something to a namespace, It gets copied (cloned) if it's a primitive. If it's an object, both namespaces then refer to the same object
var num = 5;
var prim = num;
prim++; // prim is 6, but num is still 5.
var num = {five:5};
var ob = num;
ob.five = 6;
console.log(num.five) //also 6.
A little hack that works but isn't recommended is using the process variable. You can apply different properties to it and essentially use them like you would the window object in browser-based JS. This little hack will provide a reference to the variable. It can be changed and manipulated and the change will carry over to all files that are required.
But do note that it is not recommended as overriding the process variable could have some unexpected effects and is subject to loss of information should another process interfere.
file1.js:
const s1 = require('./file2');
process.num = 2;
console.log("file1", process.num);
s1.changeNum();
console.log("file1", process.num);
file2.js:
module.exports.changeNum = () => {
process.num = 3;
console.log("file2", process.num);
};
output:
file1 2
file2 3
file1 3
alternatively, to all other answers
getters & setters
var _variableThing = 1223
module.exports = {
get variableThing(){
return _variableThing
},
set variableThing(val){
_variableThing = val
}
}
won't work with direct imports though

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