How can I push an object into an array?
Asked Answered
L

8

77

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?

Looselimbed answered 25/10, 2016 at 21:36 Comment(4)
"02": "Ramones" I assume? Also, in that case, why the array? Sounds like you want to construct a simple objectCart
Edited, yes, sorry. I will use that array with another function to create an XML file. Large history.Looselimbed
So the array will always have exactly one element? The numbered object?Cart
No, will have more objects: nietos = [{"01":"Band", "02": "Ramones"}, {"01":"Style", "02": "RockPunk"}, {"01": "", "02": "", "03" : "Another String"}] different objects with different lengths.Looselimbed
P
123

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);
Praedial answered 25/10, 2016 at 23:36 Comment(2)
Why do you need to use "01" as the key? What if I wanted to use nieto.label as the key?Calamite
@Calamite So you will have obj[nieto.label] = nieto.value;Folium
M
53

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.

Morality answered 10/7, 2017 at 11:31 Comment(2)
Why do you need to use "01" as the key? What if I wanted to use nieto.label as the key?Calamite
@Calamite Yes you can, so long as 'neito.label' is unique, you can use that as the key. But according to the question requirements the object needed to be in that format.Morality
W
15

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);
Walston answered 27/11, 2020 at 15:56 Comment(0)
P
7

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'} 
]

// add 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]

Using unshift()

const nieto = {label: 'title', value: 'ramones' } 
const modifiedObj = {01: 'title', 02: 'ramones'}

let arr = [
  {03: 'asd', 04: 'asd'}, 
  {05: 'asd', 06: 'asd'} 
]

// add the modified object to the beginning of the array
arr.unshift(modifiedObj)

console.log(arr)

The unshift() method of Array instances adds the specified elements to the beginning of an array and returns the new length of the array.

source: developer.mozilla.org

Porism answered 9/1, 2022 at 9:43 Comment(1)
if your wants to add in first index use array.unshift(modifiedObj); by the way Thanks you very much .Bland
M
1

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";
Mystify answered 25/10, 2016 at 21:42 Comment(4)
I got this error: Parse Error: Line 59: Unexpected number while parsing file. That line is: nietos[0].02 = value;Looselimbed
try nietos[0]["02"] = "Ramones"; or nietos[0][02] = "Ramones";Mystify
No. I got this error "Cannot set property '0' of undefined". Code is: var grandsons = []; grandsons[0][2] = value;Looselimbed
@pmirnd answer is updated, check the last half of the answer :)Mystify
F
1

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;
}
Fante answered 2/10, 2018 at 11:0 Comment(0)
L
0

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"}
Letta answered 25/10, 2016 at 21:42 Comment(0)
F
0

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))
Featly answered 11/1, 2022 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.