JavaScript build a dynamic object - javascript

I have a var named onversation that contains this:
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
I also have an object named person that contains this:
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
What I'd like is to have a combined object called result that looks like this
result {
conversation {
conversationId : adbabc54-3308-436d-a48b-932f4010d3c6,
participantId : 415651e6-f0a5-4203-8019-4f88c3ed9cd5
},
person {
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
}
How would I do this dynamically whereby the result object is built using the name of the var 'conversation' and name of the object 'person' ?
Also, the length of either conversation or person can be any length.
Pure JavaScript if possible , but could use underscore etc.

Try it
var result = {
'conversation': conversation,
'person': person
}
Dynamic
var result = {}
result['person'] = person
or
resilt.person = person

If I understand your question correctly, you can use object shorthand notation which is supported in most browsers (Probably all of them, except IE11) for simplifying your solution even more:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { conversation, person }
console.log(result)
EDIT:
If only the variable name changes, and it's properties names stay the same or have some sort of unique key, you can use a for loop on the object's keys.
For example:
var someConversationVariableName =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var somePersonVariableName =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { someConversationVariableName, somePersonVariableName }
for (key in result) {
if(result[key]['conversationId']) {
console.log(`Found conversation object. It's name is: ${key}`);
}
else if(result[key]['firstname']) {
console.log(`Found person object. It's name is: ${key}`);
}
}

If you need to defer adding objects, you can also take this approach:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = {};
result['conversation'] = conversation;
result['person'] = person;
console.log(result);

This Must work :-
var conversation =
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
var person=
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
var result = {
'conversation': conversation,
'person': person
}

Related

how to make a new div with jquery?

okay so, I need to create a new div using jquery with the information of a first and last name that I loop from my array.. This is what I have so far, I was wondering if I could get some help on how to make it show up on my webpage. it needs to show up like:
hello firstname lastname
hello firstname lastname
hello firstname lastname
<div id="output"></div>
function names() {
var firstAndLast = [
{name: "jane", surname: "doe"},
{name: "john", surname: "leg"},
{name: "hunny", surname: "bun"}
];
var div = $("#output");
for (var i=0; i < firstAndLast.length; i++) {
}
var div1 = $("<div>").html("Hello name surname");
$("#names").append(div1);
Your code is almost there. The main issue is that you need to put the line of jQuery which creates the div and appends it within the for loop. In addition you can retrieve the name and surname from the objects in the array using the i variable to access them by index:
var $output = $("#output");
for (var i = 0; i < firstAndLast.length; i++) {
var div1 = $("<div>").html(`Hello ${firstAndLast[i].name} ${firstAndLast[i].surname}`);
$output.append(div1);
}
That being said, the most performant way to do this would be to use map() to build an array of HTML strings which you only append to the DOM once:
function names() {
let firstAndLast = [
{ name: "jane", surname: "doe" },
{ name: "john", surname: "leg" },
{ name: "hunny", surname: "bun" }
];
let html = firstAndLast.map(o => `<div>Hello ${o.name} ${o.surname}</div>`);
$("#output").append(html);
}
names();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
You can try something like this
function names() {
var firstAndLast = [{
name: "jane",
surname: "doe"
},
{
name: "john",
surname: "leg"
},
{
name: "hunny",
surname: "bun"
}
];
let _data = firstAndLast.reduce((acc, {
name,
surname
}) => {
acc += `hello <span>${name}</span> <span>${surname}</span><br>`
return acc;
}, "")
$("#output").html(_data);
}
names()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>

Iterating through object properties/keys

I'm just starting to learn coding, and i came across this question that i could not understand.
"The second function we'll add will be called search, and it will take a first name as an argument. It will try to match the first name it receives to any of the first names in our friends contact list. If it finds a match, it will log our friend's contact information (firstName, lastName, number, address) to the console."
variables are define as follows :
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
the answer is as follows :
var search = function(name) {
for(var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
could someone better explain how did the var "key" came about ? and why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
would appreciate if someone could explain thank you.
From OP's comment:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
friends is a nested object which can also be represented like so:
friends = {
bill: {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
},
steve: {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
}
}
The for..in loop iterates over all keys in the friends object, with the variable key in your case.
why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
Because, to do that, you need to have firstName or name as a property in friends. Since those properties are nested inside (name is not event inside the nested objects), there was a for..in loop used.
You have an object friends that has 2 properties bill and steve (those are the keys). Calling friends.bill will return you an object (the value) with firstname, lastname, number, address. You need to iterate all the properties of your object friends to find the one you need
You can use Object.values(obj)
var firstNameInput = "Steve";
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
//Iterates all the friends
Object.values(friends).forEach(function(f){
//Compare the property "firstname" with the input
if(f.firstName === firstNameInput){
//Friend found
console.log(f);
return;
}
});

I created two different objects in one object. On printing them, only the last modified object is getting displayed. How to create?

var friends=new Object();
friends.bill=new Object();
friends.steve=new Object();
var friends={
bill:{
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
}
};
var friends={
steve:{
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
}
};
console.log(friends);
the output of this program is all about the object "steve". If I log "friends.steve" it logs as "undefined". I want the output to be two diffrent objects in the object friend.
You are overriding the previously create object.
Rather you should try
var friends=new Object();
friends.bill=new Object();
friends.steve=new Object();
friends.bill={
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
};
friends.steve={
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
};
console.log(friends);
To store multiple values in a variable you can use the Array.
var bill = {
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
}
var steve = {
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
}
var friends = [bill, steve];
console.log(friends);
Also, in your code, you are defining the variable friends, which overwrite the variable defined with the same name. Additionally, you can define the class for friend and can create 2 objects from the class.
function Friend(firstname, lastname, number, address)
{
this.firstname = firstname;
this.lastname = lastname;
this.number = number;
this.address = address;
}
var bill = new Friend("Bill", "gates", "address", 040404040 ,['bcd','sdad']);
var steve = new Friend("Steve", "Jobs", "address", 131313131, ['abc','sdsdsd']);
var friends = [bill, steve];
console.log(friends);
In your code you define friends variable and override again in next few lines
'var friends={
bill:{'
This will override the first object and new instance will taking place instead.
Try this code and this will solve your problem
var friends = new Object();
friends.bill = {
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
};
friends.steve ={
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
};
console.log(friends);

Model in Angular.js

Here is my code
/// <reference path="angular.min.js" />
var myApp = angular.module("myModule", []).controller("myController", function($scope) {
var employees = [{
name: "Ben",
dateOfBirth: new Date("November 23,1980"),
gender: "Male",
salary: 55000.788
}, {
name: "Sara",
dateOfBirth: new Date("May 05,1970"),
gender: "Female",
salary: 68000
}, {
name: "Mark",
dateOfBirth: new Date("August 15,1974"),
gender: "Male",
salary: 57000
}, {
name: "Pam",
dateOfBirth: new Date("October 27,1979"),
gender: "Female",
salary: 53000
}, {
name: "Todd",
dateOfBirth: new Date("December 30,1983"),
gender: "Male",
salary: 60000
}];
$scope.employees = employees;
$scope.sortColumn = "name";
$scope.reverseSort = false;
$scope.sortData = function(column) {
$scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
$scope.getSortClass = function(column) {
if ($scope.sortColumn == column)
return $scope.reverseSort ? 'arrow-down' : 'arrow-up';
return '';
}
});
I just want to ask that are employees,sortColumn and reverse sort are separate models or they belong to one model and what are the sortData and getSortClass in this files are they behavior in our model please explain...Thanks in advance.
SortData, contains the column name from which you want to sort and the reverseSort is a property of current employee object, which is set to true once the sort order is descending ( binary 0 ).
getSortClass fetch the current sort order in binary format ( 0 or 1) and update the reverseSort property accordingly.
Where to start... The variables in your codeblock all belong to the myController controller you have defined. They are instantiated when the controller is invoked through the $scope dependency, as well as any injected dependencies there may be.
sortData and getSortClass are functions declared in the scope of your controller. You cannot access them from another controller unless you traverse angulars $rootScope or using a listener. As for what those functions do, #kapil yadav has given an explanation.

Clean Method to Normalize Javascript Object Properties

I have an array of javascript objects that represent users, like so:
[
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
]
Some of the objects contain some properties but not others. What I need is a clean way to ensure ALL objects get the same properties. If they don't exist, I want them to have an empty string value, like so:
[
{ userName: "Michael",
city: "Boston",
state: "",
phone: ""
},
{ userName: "Thomas",
city: "",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
city: "",
state: "",
phone: "444-4444"
}
]
Update
I should have been a little more specific. I was looking for an option that would handle this situation dynamically, so I don't have to know the properties ahead of time.
For jQuery specific, the $.extend() option is a good one, but will only work if you know ALL the properties ahead of time.
A few have mentioned that this should probably be a server-side task, and while I normally agree with that, there are two reasons I'm not handling this at the server-side:
1) it will be a smaller JSON object if say 900 of 1000 objects only contain 1 of a possible 9 properties.
2) the "empty" properties need to be added to satisfy a JS utility that could be replaced in the future with something that doesn't care if some properties are missing.
Since you are using jQuery you can abuse $.extend
function Person(options){
return $.extend({
userName:"",
city: "",
state:"",
phone: ""
},options);
}
$.map([{}],Person)
update
Heres a way to have dynamic default properties
function mapDefaults(arr){
var defaultProperties = {}
for(var i =0; i < arr.length; i++){
$.each(arr[i],function(key){
defaultProperties[key] = "";
});
}
function Defaulter(obj){
return $.extend({},defaultProperties,obj);
}
return $.map(arr, Defaulter);
}
mapDefaults([{a:"valA"},{b:"valB"}]);
/* produces:
[{a:"valA",b:""},{a:"",b:"valB"}]
*/
Something you might try is creating a coalescing function:
function coalesceValues(val){
switch(val)
case undefined:
case null:
return '';
break;
default:
return val;
break;
}
}
Or if you wanted to forego customization for simplicity:
function coalesceValues(val){
return val || '';
}
And then apply it when assigning variables:
var city = coalesceValues(obj.city);
This way you don't need to do any crazy breakdown to array and loop or anything, you can apply it to whatever you want, and you can also customize the values you want to coalesce.
Just offering an alternative idea.
The way that is easiest to understand is probably to make a function that accepts an object and uses if statements as existence checks, assigning a default value if it doesn't find it.
function normalize(object) {
if(typeof object.userName === 'undefined') {
object.userName = 'Default Value';
}
if(typeof object.city === 'undefined') {
object.city = 'Default Value';
}
if(typeof object.state === 'undefined') {
object.state = 'Default Value';
}
if(typeof object.phone === 'undefined') {
object.phone = 'Default Value';
}
return object;
}
var userArray = [{},{},{}].map(normalize);
We can also go the constructor route and provide default values on object creation.
function User (data) {
this.userName = data.userName || 'Default Value';
this.city = data.city || 'Default Value';
this.state = data.state || 'Default Value';
this.phone = data.phone || 'Default Value';
return this;
}
var userArray = [{},{},{}].map(function(o){
return new User(o);
});
Of course this depends on one specific type of data and won't extend to other properties and isn't very DRY, but as I said, this is probably the easiest to understand from a beginner's standpoint.
var list = [
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
];
for(var i = 0; i < list.length; i++){
if(list[i].state === undefined)
list[i].state = "";
if(list[i].phone === undefined)
list[i].phone = "";
};
console.log(list);
http://jsfiddle.net/g5XPk/1/
This should probably be a server-side task, but..
If you know all the possible properties ahead of time, you could do this:
http://jsfiddle.net/BMau9/
var properties = ['userName', 'city', 'state', 'phone'];
var data = [{
userName: "Michael",
city: "Boston"
}, {
userName: "Thomas",
state: "California",
phone: "555-5555"
}, {
userName: "Kathrine",
phone: "444-4444"
}];
for (var i in data) {
for (var j in properties) {
data[i][properties[j]] = data[i][properties[j]] || '';
}
}
Fiddle
This function stores unique object keys in an array and so you can run your array of objects through it and then use one of the other supplied answers to add the keys to the objects if they do not exist:
function uniqueKeys(){
var keys=[];
function getUniqueKeys(){
return keys
}
function addObject(obj){
for (var k in obj){
keys = _.union(keys,[k]);
}
}
return {
addObj: addObject,
getKeys: getUniqueKeys
}
}
Usage:
var objArr = [{ userName: "Michael", city: "Boston" },
{ userName: "Thomas", state: "California", phone: "555-5555"},
{ userName: "Kathrine",phone: "444-4444" }];
var uniq = new uniqueKeys();
_.each(objArr, function(v){
uniq.addObj(v)
});
var keys = uniq.getKeys();
alert(keys);
vanilla js
let A = [
{
userName: "Michael",
city: "Boston",
},
{
userName: "Thomas",
state: "California",
phone: "555-5555",
},
{
userName: "Kathrine",
phone: "444-4444",
},
];
// set-difference
const diff = (a,b) => new Set([...a].filter((x) => !b.has(x)));
// all keys
const K = new Set(arr.map(o => Object.keys(o)).flat());
// add missing keys and default vals
A.forEach((e,i) => diff(K, new Set(Object.keys(e))).forEach(k => A[i][k] = ""));

Categories

Resources