How can I push an object into an array? - javascript

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?

You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);

Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.

can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);

Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]

Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";

I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}

The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}

This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

Related

How to iterate over objects in an array?

I have an array object as mentioned below;
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
I would like to extract the values of dateformat into a separate array, e.g.:
var dateArray=["apr1","apr2","apr3"];
var score=[1,2,3];
I am using a for loop to extract the index but I'm not able to get the values.
Use map to iterate over the initial array objects and return the item you want.
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
var dateArray = myArray.map(function(obj){return obj.dateformat;}),
score = myArray.map(function(obj){return obj.score});
console.log(dateArray);
console.log(score);
Here's the answer as a simple loop.
var dateArray = new Array(myArray.length);
for(var i = 0; i < myArray.length; ++i) {
var value = myArray[i];
var dateValue = value.dateformat;
dateArray[i] = dateValue;
}
You can accomplish the same using the map function:
var dateArray = myArray.map(function(value) { return value.dateformat; });
Create the empty arrays, and use forEach with an argument of 'element' (which represents each object in the array) and push esch of the properties of each object into the required array.
var dateArray=[];
var score=[];
var myArray=[
{dateformat:"apr1", score:1},
{dateformat:"apr2",score:2},
{dateformat:"apr3",score:3}
];
myArray.forEach(function(element) {
dateArray.push(element.dateformat);
score.push(element.score);
});
console.log(dateArray); //gives ["apr1","apr2","apr3"]
console.log(score); //gives ["1","2","3"]
You could use a single loop approach of the given array and iterate the keys and push the values to the wanted arrays.
var myArray = [{ dateformat: "apr1", score: 1 }, { dateformat: "apr2", score: 2 }, { dateformat: "apr3", score: 3 }],
dateArray = [],
score = [];
myArray.forEach(function (target, keys) {
return function(a) {
keys.forEach(function(k, i) {
target[i].push(a[k]);
});
};
}([dateArray, score], ['dateformat', 'score']));
console.log(dateArray);
console.log(score);
If only you don't want to hard code the variables, you could use Array#forEach and Object.keys to store each unique key values inside e.g. array.
Note: It doesn't matter how many keys do you have in your objects, following solution will always return you the right output. Mind that you don't even have to initially declare new variables.
var myArray = [{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}],
obj = {};
myArray.forEach(v => Object.keys(v).forEach(function(c) {
(obj[c] || (obj[c] = [])).push(v[c]);
}));
console.log(obj);

Push datas into a multidimensional array in JS

I'm trying to push some datas into my array.
Actually my code looks like this:
arr.push('step1||item1||99');
It works but it's not the best as I need to split it after to manager datas.
How can I transform this into a multidimensional array ?
What I tried:
arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);
But it doesn't work...
Any help please.
Is there a reason you don't want these individual data points to be objects?
var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);
If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?
Array holds "indexes"
Object holds "Key" and "Value"
Array example:
var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);
Object example:
var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);
Objects in array:
var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;
arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]
maybe you mean something like this
arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);
s is an object, which works just like an array, but is referenced by a string instead of an integer:
s['step'] === 'step1'
s.step === 'step1'
arr[0] === s
Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.

Javascript, retrieve array name

I have this:
var one = ['12','24','36'];
var two = ['10','20','30'];
If I do:
alert(one) I have: 12,24,36. And it's ok.
I need to have the name of the array from another function, where I call it from a for like this:
var test = [one,two]
for (i = 0; i < test.length; i++) {
alert(test[i]);
}
I have "12,24,36" and then "10,20,30" in the alert, but I need the name of the array, not the content. How to do?
I want two alert with: "one" and "two", the name of Array.
Use an object to hold your arrays:
var obj = {
one: ['12','24','36'],
two: ['10','20','30']
}
for (var p in obj) {
console.log(p); // log the key
}
Alternatively you can use Object.keys(obj) to retrieve an array of the object keys.
And if you need to log the array contents:
for (var p in obj) {
console.log(obj[p]); // log the array contents
}
DEMO
Yes, I agree with elad.chen. You can try something like:
var objects = [
{name:"one",value:['12','24','36']},
{name:"two",value:['12','24','36']}
];
for(var i=0;i<objects.length;i++){
console.log(objects[i].name);
console.log(objects[i].value);
}
You can use an "Object Literal" and use the property name as the name, and the value as the array..
For example:
var arrays = {
"one": [1,2,3],
"two": [1,2,3]
}
for ( var k in arrays ) {
alert('"Array name" = ' + k)
alert('"Array value" = ' + arrays[k].toString() )
}
At some place, the name must be set. While Javascript is can add properties to objects, this can be used for a name property without changing the behaviour of the arrays.
var one = ['12', '24', '36'];
one.name = 'one';
var two = ['10', '20', '30'];
two.name = 'two';
var test = [one, two], i;
for (i in test) {
document.write(test[i].name + '<br>');
}

Convert Array of Javascript Objects to single simple array

I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.
Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]
How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});

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