How can I add the data of one JS object to another - javascript

In the function there is an empty JS object
var globalDataObject = [{}];
Then, there is a loop that goes over an array of users, stores the properties of each user in variables (ex. name, lastName, ...) and creates an object for each user:
//create an object containing the current name
const currentObject = {
'profile': {
'name': nameVariable,
'lastName': lastNameVariable
}
};
What is the right way to add the data of currentObject to the globalDataObject once it's created? So that at the end the globalDataObject should be:
var globalDataObject = [
'profile': {
'name': 'John',
'lastName': 'Smith'
},
'profile': {
'name': 'Ann',
'lastName': 'Lee'
},
'profile': {
'name': 'Dan',
'lastName': 'Brown'
}
];
Important thing is that globalDataObject must be the JS object of the specified format (not the object containing multiple objects and not the array) since once it's created it is going to be converted into XML.

You can create your global object like an array:
globalDataObject = [];
And then just push in it:
globalDataObject.push(currentObject);

I dont understand the end goal of the question and why you dont just use .push() as suggested before. You havent accepted that answer so i assume its not the end goal.
globalDataObject must be the JS object of the specified format (not
the object containing multiple object and not the array)
1) The format you gave is not valid JavaScript.
2) Why cant you have an array of objects or object with nexted objects and covert that into xml
3) Why do you want to convert json into xml in the first place.
I'll take a wild guess and assume you mis-typed the globalDataObject as array, and meant it to be an object with multiple 'profile' keys. Neither is valid javascript.
Since you can't have multiple keys with same name and expect them to have different values, I propose you to use unique "indexes" for each profile.( like an array...but an object).
// init the object
const userProfiles = {};
// then later add to it like this.
let profile1 = {name: "john", lastname: "smith"};
let profile2 = {name: "alice", lastname: "wonderland"};
userProfiles[1] = profile1;
userProfiles[2] = profile2;
// you can then torn it into an array of user profile objects like this
Object.keys(userProfiles).map((index) => {return userProfiles[index];})

Related

Insert objects without matching column name

This is probably a silly question, but I am new to node and postgresql, so I am struggling.
I am trying to use pgp.helpers.insert to insert multiple objects into the database, as the example bellow:
users = [{mycolumn:{name: 'John', age:23}}, {mycolumn:{name: 'Mike', age: 30}}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// insert into "mytable"("mycolumn") values('{"name":"John","age":23}'),('{"name":"Mike","age":30}')
The code above inserts into mytable 2 rows with mycolumn as a jsonb.
But I am trying to insert straight into mycolumn the values inside an array of objects, without wrapping my original object, such as:
users = [{name: 'John', age:23}, {name: 'Mike', age: 30}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// Error: Property 'mycolumn' doesn't exist.
Of course it doesn't work, since the object doesn't contain a mycolumn attribute. But I think it is not elegant to iterate in my array wrapping the original object with the column name, specially since I am working with millions of rows (working in batches, of course).
Thanks in advance.
You can use the following definition for your column, as per the Column syntax:
{
name: 'mycolumn',
init: c => c.source // use the source object itself
}
i.e.
const cs = new pgp.helpers.ColumnSet([
{
name: 'mycolumn',
init: c => c.source
}
], {table: 'mytable'});
and then use it:
const query = pgp.helpers.insert(users, cs);
Note that we are not specifying the modifier - mod: ':json', because we are returning an object from init, and objects are formatted as JSON by default.

How to pass by reference (simulation)

I'm having a trouble approaching to this problem, althouh I have a working solution I doubt it is the most optimal one.
Here is the problem:
Imagine an array of objects, each object represents a person.
var people = [
{id:1, name:"John", points: 50},
{id:2, name:"Mark", points: 80},
{id:3, name:"Peter", points: 25},
];
In our people array, we have 3 persons with an unique id property.
Now imagine that we have multiple functions that modify/update person objects.
Obviously this wouldn't work, since the outer object won't be affected
by the changes made in incrementPoints() function.
var myPerson = people[0];
incrementPoints(myPerson){
myPerson.points++;
};
// myPerson.points = 50
addPoints(myPerson); // We're passing an person object to addPoints;
// myPerson.points = 50 (Did not change, not affected by addPoints)
This however, would work! But the price we pay is the cost of
iteration through persons array and matching the id of desired person.
function getPersonIndexById(personId){
// Iterate through all persons in 'people' array
for(var index = 0; index < people.length; index++)
people[i].id === personId ? return index : continue;
}
function incrementPoints(personId){
people[ getPersonIndexById(personId) ].points++;
}
function decrementPoints(personId){
people[ getPersonIndexById(personId) ].points--;
}
Is there a better/simpler/cleaner/intended concept for dealing with such situations. Obviously, the ideal solution would be a pass by &reference but javascript does not allow that. I'm not trying to do achieve an useless hack, but rather get understanding of what developers do when they stumble upon similar situations and how they solve them.
var people = [
{id:1, name:"John", points: 50},
{id:2, name:"Mark", points: 80},
{id:3, name:"Peter", points: 25},
];
var myPerson = people[0];
function incrementPoints(myPerson){
myPerson.points++;
};
function addPropertyToPerson(myPerson, lastname) {
myPerson.lastName = lastname;
}
// The properties of the myPerson object can still be modified since
// the value passed in to the function is the reference to the object
incrementPoints(myPerson);
console.log(myPerson);
// Similarly, additional properties can still be added since
// the value passed in to the function is the reference to
// the outer object
addPropertyToPerson(myPerson, "smith");
console.log(myPerson);
Objects are passed as reference
You defined a function with name incrementPoints with a wrong syntax but you are calling addPoints. I hope it is a typo/mistake.
if I suppose it is addPoints then it is working fine. You will get 51 points after that function call.
You can use Array.prototype.find to find a person by id, it is builtin and it will be fast.
function incrementPoints(personId){
var person = people.find(function(p){
return p.id === personId;
});
if (person) {
person.points++;
}
}
I would prefer to convert array to map while getting data.
var personMap = {}; people.forEach(function(person){
personMap[id] = person;
});
With this now you have map
You can get person as personMap[personId]
Here creating map is one time activity so you need a single round of iteration
Please bear with my response.. I am replying from mobile so formatting might be not good

return object via array values

I have an object and would like to find and return the object values based on an array.
var profile = {
'firstName' : 'John',
'lastName' : 'Doe',
'mood' : 'happy'
};
var updated= ['firstName','mood'];
The updated array gets changed with the key when a the relevant field has been changed.
Thanks.
I have an object and would like to find and return the object values based on an array.
You don't need underscore.js for this. You can do this with plain js simply by iterating over the array and extracting the necessary properties from your object:
var profile = {
'firstName': 'John',
'lastName': 'Doe',
'mood': 'happy'
};
var updated = ['firstName', 'mood'];
updated.forEach(function(prop) {
console.log(profile[prop]);
});
The updated array gets changed with the key when a the relevant field has been changed.
Not sure I understand you exactly, but it seems that you want an array of values for properties of the profile object whose names are contained in the updated array. Using Array.prototype.map would do the trick:
var profile = {
'firstName': 'John',
'lastName': 'Doe',
'mood': 'happy'
};
var updated = ['firstName', 'mood'];
var values = updated.map(function(prop) {
return profile[prop];
});
console.log(values);
Seeing that you asked for an underscore solution, here's one:
Pick returns an object with just the keys that you want:
var result = _.pick(profile, updated);
So result will look like:
{
'firstName' : 'John',
'mood' : 'happy'
}
If you need just the values in an array then use the values function:
var values = _.values(result);

concatenate fields in JS multidim Array, sort, then create different type of JS object array

I want to take an array that looks like the following:
var contacts = [
{account: 'Acme', firstName: 'John', lastName: 'Snow'},
{account: 'Metal Industries', firstName: 'Ted', lastName: 'Smith'}
];
Note: contacts can have the same account name.
and create a function to convert the data to something that instead is an object with the following structure that's like a map where the key is account name and value is an array of alphabetized full names as below:
var acctContactObject = {
'Acme': ['John Snow','Kyle Johnson','Sara Butler'],
'HiTech Corp': ['Arnold Williams','Jason Fernandez','Sam Johnson']
};
I'm not certain that I'm taking the correct approach and wanted to seek some sage advice before proceeding. Here's what I've written so far and "psuedocode" for where I'm heading.
function convertAccountArrayToObject(contacts){
this.account = contacts.account;
this.firstName = contacts.firstName;
this.lastName = contacts.lastName;
this.sort(function(a, b) {
return a.account.localeCompare(b.account);
});
var aco = new acctContactObject();
var name;
var nameArray = [];
for(var member of this){
//this is where I get stuck
//I could create a new array to hold the account with full name
//but somehow need to add them to an array that I can sort on
//
//assuming I used an intermediate array...
//create new acctContactObject
//For acct in intermediate array
//add name to another single array and sort alphabetically
//put acct name and sorted list of names into new object
//after end of loop, return object
I've been searching to see if there's a way to do a secondary sort on a multidimensional array, but didn't find what I was looking for. I've also run across mention of "merging" properties, but am not certain if that would allow me to concatenate the values for the first and last names properly.
I don't do a lot of JS, at least not of this kind, so would appreciate knowing if I'm on the right track. Any suggestions or guidance towards a cleaner way to approach this would be appreciated.
The simplest way to do it will be as follows.
Note:I have modified contacts to include the case of same account names.
var contacts = [
{account: 'Acme', firstName: 'John', lastName: 'Snow'},
{account: 'Metal Industries', firstName: 'Ted', lastName: 'Smith'},
{account: 'Metal Industries', firstName: 'Bolt', lastName: 'Coder'}
];
function convertAccountArrayToObject(contacts){
var returnObj={},key;
contacts.forEach(function(v,i){
key=v.account;
if(!returnObj[key]){
returnObj[key]=[];
}
returnObj[key].push(v.firstName+" "+v.lastName);
});
return returnObj;
}
acctContactObject=convertAccountArrayToObject(contacts);
Upvote if you find this helpful.

Converting array in object to string

I want the array in an object to be a string. can someone pl help? So im passing an array into an object and Im expecting var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort'; how can this be attained ?
it("should serialize an object with another object/array in it", function() {
var object2 = {
'name': 'bob',
'age': 24,
'kids': [ 'billy', 'bart', 'bort' ]
};
var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort';
expect(NUUI.Utils.serializeForQueryString(object2))
.toEqual(expectedResultForObject2);
});
You need serialized result from an object. This can be achieved with jQuery.param()
uri = $.param(object2);
More information on this, you can find in jQuery Manual.
Alternatively, you can make an array object a string simply with .join() method of the array
string = array.join('');
This question is heavily answered in SO
jQuery serialize an object?

Categories

Resources