Javascript object in array - javascript

Lets say I have a object like
> var products = {a:"b", c:"d", e:"f" ... it goes like this}
i want to put this object in array like this
> var arrList = [[a,b],[c,d],[e,f]]
but i couldnt managed it'll be great if you guys help me thank you already

Just loop and add it to the array
var result = []
for (var key in products) { result.push([key,products[key]]) }

One possible approach:
var arrList = Object.keys(products).map(function(key) {
return [key, products[key]];
});
Note, though, that properties order in objects are not guaranteed in JavaScript.

You can proceed like this:
var products = {a:"b", c:"d", e:"f"};
var arrList = [];
for(var key in products) { // iterates over products key (e.g: a,c,e)
arrList.push([key, products[key]]);
};

Use for-in loop to iterate through object
for (variable in object) => variable is a property name
Try this:
var products = {
a: "b",
c: "d",
e: "f"
};
var arr = [];
for (i in products) {
arr.push([i, products[i]]);
}
snippet.log(JSON.stringify(arr));
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

You can do it as follow
products = {a:"b",c:"d",e:"f"};
arrList = [];
for(i in products){
arrList.push([i,products[i]]);
}

Related

How to merge the below arrays in javascript?

I have two arrays and I want to join them
function test()
{
var arr1 = [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
];
var arr2 = [
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
];
var res = Pack(arr1,arr2);
console.log(res);
}
function Pack()
{
var args = [].slice.call(arguments);
args.join(',');
return args;
}
I am expecting the output as
[{"Employees":[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}],"Departments":[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}]}]
But not able to. How to do it?
I have already tried with Concat() function of Javascript but it didn't helped.
N.B.~ As it can be assumed that there can be variable number of arrays in the Pack function.
Couldn't you do something like:
var newArray = [ { "Employees": arr1, "Departments": arr2 } ]
Try this:
var arr1 = [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
];
var arr2 = [
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
];
var json = {};
var jsonArr = [];
json.Employees = arr1;
json.Department = arr2;
jsonArr.push(json);
document.write(JSON.stringify(jsonArr));
From the expected JSON, what you need is neither "merging", nor "concatenation". You want to put an array inside an object.
What you want is below:
var output = [{
"Employees": arr1,
"Department": arr2
}];
Note that output is an array according to your expectation. Why you need an array is something I dont understand.
Ok, so i put a little fiddle together for you, Here
Most of your code stays the same, except I added this to your test function:
var myObjToMerge = [{Employees:[]},{Departments:[]}];
var res = Pack(myObjToMerge,arr1,arr2);
You need to give 'Pack' some object to merge the arrays to, so I created an arbritary array of objects modeled after your example. Note that this array of objects can come from anywhere and this method doesn't require it to be known ahead of time like some of the other examples.
Then I changed the 'Pack' function:
function Pack()
{
var objToMerge = arguments[0];
for(var i = 0;i<objToMerge.length;i++)
{
if(arguments.length > i+1)
{
var firstProperty = Object.keys(objToMerge[i])[0];
objToMerge[i][firstProperty]= arguments[i+1];
}
}
return objToMerge;
}
The idea here is that 'Pack' grabs the first argument, your object to merge the remaining arguments into. I would suggest using function parameters, but that is your call.
Then, I iterate through the objects in the objToMerge array (there are two objects: Employees and Departments).
I assume that the remaining items in arguments is in the correct order and I grab the next item in arguments and assign to to the first property in the object I am currently looped in.
The line:
var firstProperty = Object.keys(objToMerge[i])[0];
Will return the string value of the first property in an object. We then use this to set the next array in arguments to that property:
objToMerge[i][firstProperty]= arguments[i+1];
there are a great deal of assumptions here and ways to improve, but you can see that it works in the fiddle and you can improve upon it as needed.
function test() {
var arr1 = {"Employees" : [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
]};
var arr2 = {"Departments":[
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
]};
var res = Pack(arr1,arr2);
console.log(res);
}
function Pack()
{
var results = [];
arguments.forEach(function(element){
results.push(element);
});
return results;
}

Returning only certain properties from an array of objects in Javascript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
If I have an object such that
var object = function(key,text)
{
this.key = key;
this.text = text;
}
And create an array of these objects
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:
var keyArray = objArray["key"];
The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:
keyArray = [
'key1',
'key2',
'key3']
Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?
This is easily done with the Array.prototype.map() function:
var keyArray = objArray.map(function(item) { return item["key"]; });
If you are going to do this often, you could write a function that abstracts away the map:
function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}
In fact, the Underscore library has a built-in function called pluck that does exactly that.
var object = function(key,text) {
this.key = key;
this.text = text;
}
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
var keys = objArray.map(function(o,i) {
return o.key;
});
console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
http://jsbin.com/vamey/1/edit
Note that older browsers may not support map but you can easily do this with a for loop:
var keys = [];
for (var i = 0; i < objArray.length; i++) {
keys.push(objArray[i].key);
}
JS Bin Example
http://jsbin.com/redis/1/edit
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) {
var i = arr.length;
arr = arr.slice();
while (i--) arr[i] = func(arr[i]);
return arr;
}
Well something has to iterate through the elements of the array. You can use .map() to make it look nice:
var keys = objArray.map(function(o) { return o.key; });
You could make a function to generate a function to retrieve a particular key:
function plucker(prop) {
return function(o) {
return o[prop];
};
}
Then:
var keys = objArray.map(plucker("key"));
Really "objArray" is an array that have 3 objects inside, if you want list of keys, you can try this:
var keys = [];
for(a in objArray) {
keys.push(objArray[a].key);
}
You have in var keys, the three keys.
Hope that helps! :)

How to convert Object into array in jquery/javascript

I want to convert an object with specific properties into array of string containing properties values. For an instance take Object Employee with below properties with values
Employee.Name='XYZ'
Employee.ID=123
Employee.Address='ABC'
I want this all to be in array as
var arr=['XYZ',123,'ABC']
How to iterate over the properties. Is this possible? Please assist here.
Use $.map()
var arr = $.map(Employee, function(value, key){
return value
})
Demo: Fiddle
Note: The order of loop is not dependable, so the order of values in the array may not be always same
Another way to handle it is to use a fixed array of keys so that the output array will have a predefined sequence
var keys = ['Name', 'ID', 'Address'];
var Employee = {};
Employee.Name = 'XYZ'
Employee.ID = 123
Employee.Address = 'ABC'
var arr = $.map(keys, function (key, idx) {
return Employee[key]
})
console.log(arr)
Demo: Fiddle
Loop through the object like this
var arr = [];
for (var key in Employee) {
arr.push(Employee[key]);
}
Note: Order is not defined in this case
You can loop through each property and add it's value to the array:
var arr = [];
for (var prop in Employee) {
if (Employee.hasOwnProperty(prop)) {
arr.push(Employee[prop]);
}
}
Example - http://jsfiddle.net/infernalbadger/2PHpZ/
Or using jQuery:
var arr = $.map(Employee, function(propValue) {
return propValue;
});
Example - http://jsfiddle.net/infernalbadger/2PHpZ/1/
var myArray=[];
for (var key in Employee) {
if (Employee.hasOwnProperty(key)) {
myArray.push(Employee[key]));
}
}
var Employee = {};
Employee.Name='XYZ';
Employee.ID=123;
Employee.Address='ABC';
var empArray =[];
$.each(Employee,function(item){
empArray.push(item);
});
console.log(empArray);
fiddle
JavaScript since 1.7. Reference to JavaScript language advanced Tips & Tricks.
var arr = [Employee.Name,Employee.ID,Employee.Address];

Push an object into the object list object

The simplest question ever, and I did not find right answer yet.
Got object list: object_list = {}
Got object: object_x = {...}
How do I add object_x to object_list[objects_x]?
I tried: object_list[objects_x][object_list[objects_x].length] = object_x, but object_list[objects_x].length is undefined.
push() does not work either.
Do I really need to define external counter for that?
PLEASE NOT THAT I MEAN LIST OF LISTS OF OBJECTS. NOTE THE DIFFERENCE BETWEEN objects_x and object_x.
There is no simple solution like in PHP where you simply $array['something'][] = $somedata ?
object_list['object_x'] = object_x;
// or
object_list.object_x = object_x;
console.log(object_list.object_x === object_list['object_x'])
How to work with objects - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
When you create a variable like var stuff = {}, you're creating an empty object literal, it has no attributes (properties or methods) other than what it inherits from Object. If you want to keep objects stored in various lists in this object you need to first create those lists.
var stuff = { shelves: [], selectors: [], images: [], additional: [] };
Now you can add whatever you want to those lists as much as you want.
var image = { src: '/path/to/image.jpg' };
stuff.images.push(image);
You can add more lists to stuff whenever like by just setting the new property on stuff.
stuff.some_other_list = []
Hope it helps.
Your base assumption is wrong.
This:
var object_list = {}
Is not a list. It's not an array and you can't reference its items by index, thus it also does not have .length property.
What you are after is a plain array:
var object_list = [];
Now you can push items into it:
object_list.push(object_x);
Edit: based on your comments and edits, I think what you're really after are couple of helper functions:
function AddToList(list, item) {
var counter = 0;
for (var key in list)
counter++;
var key = "item_index_" + counter;
list[key] = item;
}
function GetItemByIndex(list, index) {
var counter = 0;
var existingKey = "";
for (var key in list) {
if (counter == index) {
existingKey = key;
break;
}
counter++;
}
return (existingKey.toString().length > 0) ? list[existingKey] : null;
}
Having those, you can have such a code now:
var mainList = {};
var newItem = { "foo": "bar" };
AddToList(mainList, newItem);
var dummy = GetItemByIndex(mainList, 0)["foo"]; //will contain "bar"
Live test case.
If you are interested use object, not array, you can use like this:
var object_list = {};
var object_x = {'prop1':'val1'};
// add object
object_list.myobj = object_x;
// for access, same scheme.
object_list.myobj.prop1 = 'valX';
// for loop thru
for (var key in object_list) {
var obj = object_list[key];
obj.prop1 = 'valY';
}

Declaring array of objects

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.
var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();
This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?
var sample = new Array();
sample[] = new Object();
I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
Depending on what you mean by declaring, you can try using object literals in an array literal:
var sample = [{}, {}, {} /*, ... */];
EDIT: If your goal is an array whose undefined items are empty object literals by default, you can write a small utility function:
function getDefaultObjectAt(array, index)
{
return array[index] = array[index] || {};
}
Then use it like this:
var sample = [];
var obj = getDefaultObjectAt(sample, 0); // {} returned and stored at index 0.
Or even:
getDefaultObjectAt(sample, 1).prop = "val"; // { prop: "val" } stored at index 1.
Of course, direct assignment to the return value of getDefaultObjectAt() will not work, so you cannot write:
getDefaultObjectAt(sample, 2) = { prop: "val" };
You can use fill().
let arr = new Array(5).fill('lol');
let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));
Will create an array of 5 items. Then you can use forEach for example.
arr.forEach(str => console.log(str));
Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.
After seeing how you responded in the comments. It seems like it would be best to use push as others have suggested. This way you don't need to know the indices, but you can still add to the array.
var arr = [];
function funcInJsFile() {
// Do Stuff
var obj = {x: 54, y: 10};
arr.push(obj);
}
In this case, every time you use that function, it will push a new object into the array.
You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use push as Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.
var samples = []; /* If you have no data to put in yet. */
/* Later, probably in a callback method with computed data */
/* replacing the constants. */
samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
/* or */
samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */
I believe using new Array(10) creates an array with 10 undefined elements.
You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):
var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });
Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
//making array of book object
var books = [];
var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
books.push(new_book);
new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
books.push(new_book);
console.log(books[0].id);
console.log(books[0].name);
console.log(books[0].category);
console.log(books[0].price);
// also we have array of albums
var albums = []
var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
albums.push(new_album);
new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);
console.log(my_albums[0].name);
console.log(my_albums[1].name);
This Example Works with me.
Snapshot for the Output on Browser Console
Try this-
var arr = [];
arr.push({});
const sample = [];
list.forEach(element => {
const item = {} as { name: string, description: string };
item.name= element.name;
item.description= element.description;
sample.push(item);
});
return sample;
Anyone try this.. and suggest something.
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
you can use it
var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
sample.push({})
OR
sample.push(new Object())
}
Using forEach we can store data in case we have already data we want to do some business login on data.
var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];
sample.forEach(function(item){
data.push(item);
})
document.write(data);
Example by using simple for loop
var data = [];
for(var i = 0 ; i < 10 ; i++){
data.push(i);
}
document.write(data);
If you want all elements inside an array to be objects, you can use of JavaScript Proxy to apply a validation on objects before you insert them in an array. It's quite simple,
const arr = new Proxy(new Array(), {
set(target, key, value) {
if ((value !== null && typeof value === 'object') || key === 'length') {
return Reflect.set(...arguments);
} else {
throw new Error('Only objects are allowed');
}
}
});
Now if you try to do something like this:
arr[0] = 'Hello World'; // Error
It will throw an error. However if you insert an object, it will be allowed:
arr[0] = {}; // Allowed
For more details on Proxies please refer to this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
If you are looking for a polyfill implementation you can checkout this link:
https://github.com/GoogleChrome/proxy-polyfill
The below code from my project maybe it good for you
reCalculateDetailSummary(updateMode: boolean) {
var summaryList: any = [];
var list: any;
if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList }
else {
list = this.state.chargeDefinitionList;
}
list.forEach((item: any) => {
if (summaryList == null || summaryList.length == 0) {
var obj = {
chargeClassification: item.classfication,
totalChargeAmount: item.chargeAmount
};
summaryList.push(obj);
} else {
if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) {
summaryList.find((x: any) => x.chargeClassification == item.classfication)
.totalChargeAmount += item.chargeAmount;
}
}
});
if (summaryList != null && summaryList.length != 0) {
summaryList.push({
chargeClassification: 'Total',
totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount
})
}
this.setState({ detailSummaryList: summaryList });
}
var ArrayofObjects = [{}]; //An empty array of objects.

Categories

Resources