Create Javascript object with one array property - javascript

How to create a javascript object runtime like following
task{
timestamp:string;
tasklist: array of object
}

You can use an object initialiser for that:
var task = {
timestamp: "this is a string",
tasklist: []
};
[] creates an array (an empty one). JavaScript doesn't have "array(s) of object," a standard array can hold anything. (JavaScript does, these days, have typed arrays for other things, like 8-bit integers, but not objects.)

var task = {
timestamp: new Date().getTime(),
tasklist: [new Object(), new Object()]
};
This could be one way to do it. Then you can get access to the property in this way:
task.tasklist[i...n]
You could also create an array like this:
var task = []
and then assign the timestamp as a property:
task.timestamp = //myTimestamp

var task = {};
task.timestamp = 'your string';
task.tasklist = [];
and then add task list objects like:
task.tasklist.push({'id': 5, 'name': 'task list 5'});
or:
var tasklistentry = {};
tasklistentry.id = 5;
tasklistentry.name = 'task list 5';
task.tasklist.push(tasklistentry);

Related

Javascript finding combined properties from an array and object keys

I have an object. I would like to be able to dynamically create an array, then create another object that contains the key-value pairs that correspond with properties from the array that I created.
For example, if I have the following object...
var churchMembers = {
John: 'fsiolfjdklsjds#yahoo.com',
Betty: 'fowifj#hotmail.com',
Christopher: 'fsis#yahoo.com',
James: 'wfowji#gmail.com',
Deep: 'abab#msn.com'
};
and I create the following array:
var peopleComing = ['John', 'Christopher', 'James'];
I want the following response
var peopleList = {
John: 'fsiolfjdklsjds#yahoo.com',
Christopher: 'fsis#yahoo.com',
James: 'wfowji#gmail.com'
};
Right now I'm trying to use a for loop and all I'm doing is iterating through the object properties, which is not giving me anything. Going with the Object.keys route seems counterproductive, although that would easily allow me to filter out the correct names. Thanks. SIAP
You can use Array#forEach to iterate over your list of names, and get the email for each name and add it to your peopleList.
var peopleList = {};
peopleComing.forEach(function(name){
peopleList[name] = churchMembers[name];
});
Ignoring the typo you have in your code, the below code should be capable of initializing peopleList with what you want.
var churchMembers = {
John: "fsiolfjdklsjds#yahoo.com"
Betty: "fowifj#hotmail.com",
Christopher: "fsis#yahoo.com",
James: "wfowji#gmail.com",
Deep: "abab#msn.com"
},
peopleComing = ["John", "Christopher", "James"],
peopleList = {};
for (var i = 0, j = peopleComing.length; i < j; i++) {
peopleList[peopleComing[i]] = churchMembers[peopleComing[i]];
}

convert array of objects into simple array nodejs

I am creating project using nodejs. I want to convert array of objects into simple array.For example
var test = [ { id: '1111',
type: 'sdfsdf'
},
{ id: 'df45',
type: 'fsdsdf',
}]
I need
var actual = [111,'sdfsdf'], ['df45','fsdsdf'].
I would propose this solution based on a dynamic number of keys:
var arr = test.map(function(obj){
return Object.keys(obj). // convert object to array of keys
reduce(function(arr, current){arr.push(obj[current]); return arr}, []); // generate a new array based on object values
});
This can be done using Array.map() as follows:
var actual = []
test.map(function(object) {
actual.push(objectToArray(object))
})
function objectToArray(obj) {
var array = []
// As georg suggested, this gets a list of the keys
// of the object and sorts them, and adds them to an array
var obj_keys = Object.keys(obj).sort()
// here we iterate over the list of keys
// and add the corresponding properties from the object
// to the 'array' that will be returned
for(var i = 0; i < obj_keys.length; i++) {
array.push(obj[obj_keys[i]])
}
return array
}
The function objectToArray takes any object and turns it into an array so that it can be flexible regardless of the keys within the object.

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

Array of email objects in Javascript

I need to use an array of emails whose each record should point to several attributes like To, From, and Subject. I did something like this:
var emailAttr = new Array("to","from","subject");
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2"; // This line gives exception that emails[1] is undefined
What am i missing and how can i make it work so that I can access elements like emails[i].to ?
var emailAttr = new Array("to","from","subject");
This creates a new array with the values:
0: "to"
1: "from"
2: "subject"
Then
var emails = new Array(emailAttr);
This creates a new array consisting of one value:
0: The array you created in the previous line
Then this:
emails[0].to = "abc1";
adds a new property to the first array:
0: "to"
1: "from"
2: "subject"
to: "abc1"
and then this:
emails[1].to = "abc2";
… tries to do the same to the second item in the emails array, but you haven't assigned an array there so you are trying to set a property on the undefined object which isn't allowed and you get an error.
You probably want to create an array (for your ordered list of email objects) of objects (not arrays, use objects for named values, use arrays for numerically indexed, ordered values), and you need to create a new object for each member.
var emails = [];
emails.push({
to: "abc1",
from: "...",
subject: "..."
});
You can then repeat that to add any many items as you like.
You can edit items in it (but only ones you have already created) using your original syntax:
emails[0].to = "abc1";
NB: Best practise is to use the [] and {} literals to create new arrays and objects, not the constructor functions Array() and Object().
You should make the email an object and push those into an emails array:
// Create emails array
var emails = [];
// Create an email object
var emailObj = {
to: 'mail#mail.com',
from: 'anothermail#mail.com',
subject: 'Hello there'
};
// Add the email to the emails array
emails.push(emailObj);
// Will console log "Hello there"
console.log(emails[0].subject);
You first have to define what the child object is. When you write emails[1].to, you're already trying to access that sub object before it's been defined.
Change it to:
emails = []; // create the main array
emails[0] = {to: 'abc1'}; // define an object and assign it to the main array
emails[1] = {to: 'abc2'};
You have to create an array which consists of objects.
So instead of these lines
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2";
you can simply write this:
var emails = [{
to: "abc1"
}, {
to: "abc2"
}];

Working with Java Script and multidimensional arrays

I am currently working on a website type project and I am new to JavaScript. So I have been having troubles with some parts of the syntax. Basically I am trying to print the 'id' and 'value' in the nested array arr.
var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})};
var obj = myArray[0];
document.write(obj.id);
this will print the id 1 but im not sure how to access id 10.
Also if there is an easier way to do this let me know please!
Firstly, don't use the new Array constructor. Just define an array literal [...]. So your myArray will look like:
var myArray = [{id:'1', value:'een', arr: [{id:'10', value:'een'}]}];
To get to the id of 10, you need to access myArray[0].arr[0].id;.
Proper reference would be:
obj.arr[0].id
PS: google chrome developer console is a goot playground for testing javascript object dereefrecing
You can't without iterating over the array.
If order does not matter, use an object instead:
var myObject = {
1: {id:'1', value:'een'},
10: {id:'10', value:'een'}
};
var obj = myArray[10];
document.write(obj.id);
In case the nesting in your array is intended, here's what you want:
var obj = myArray[0].arr[0];
Demo:
> var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})});
> myArray[0].arr[0]
{ id: '10', value: 'een' }
I would for get arrays why not create your own object ?
http://www.w3schools.com/js/js_objects.asp

Categories

Resources