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);
Related
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];})
In JavaScript does the placement and ordering when using spread syntax matter?
var item = {/* key value pairs here */};
var itemB = {/* key value pairs here */};
For example in the following code snippets will newItem always have the same key value pairs?
var newItem = {
...item,
...itemB
};
as
var newItem = {
...itemB,
...item
};
Besides just the general order of the key value pairs, which doesn't really have a super major impact on the result of the object, the only other difference would be if item and itemB have duplicate keys.
For example.
var item = {firstName: "Bob"};
var itemB = {lastName: "Smith", firstName: "Tim"};
In this case the following two items will not be identical.
var newItem = {
...item,
...itemB
};
// {lastName: "Smith", firstName: "Tim"}
var newItem = {
...itemB,
...item
};
// {lastName: "Smith", firstName: "Bob"}
So if there are duplicate keys, the order of the objects being spread does matter.
This can be especially useful if you wish to provide default key value pairs for an object. You can just put the default key value pairs first and it will act as defaults for the new object if they don't exist in the object that is being used with the spread syntax.
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.
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.
I have a array for store object, which have an object in it already:
var obj = [{
name: 'json',
lang: 'en'
}];
console,.log(obj) //the result is OK;
then I want push another object into it, just like:
var newObj = {
name: 'lee',
lang: 'zh'
}
obj.push(newObj)
but after this I print the obj array,console.log(obj), the result is 2 !!
Why this happen? How can I solve this problem?To store object in array correctly
Make sure you didn't do obj = obj.push(newObj);, because .push method returns the number of elements after push; instead, the line should simply read obj.push(newObj).