push object into array

JavascriptArraysJsonObjectArray Push

Javascript Problem Overview


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 objects into the nietos array?

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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.

Solution 3 - Javascript

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);

Solution 4 - Javascript

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";

Solution 5 - Javascript

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"}

Solution 6 - Javascript

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;
}

Solution 7 - Javascript

Using destructuring assignment (ES6)

const obj = {label: "Title", value: "Ramones" } // Modify the object

let restOfArray, 
    array = [
      {'03': 'asd', '04': 'asd'}, 
      {'05': 'asd', '06': 'asd'} 
    ];

let modifiedObj = {'01': obj.label, '02': obj.value}

[...restOfArray] = array // Unpack the objects inside the array

array = [modifiedObj , ...restOfArray] // Push the modified object to the first index 

console.log(array)

If you'd like to push it to the last index just change ...restOfArray to the front.

array = [...restOfArray, modifiedObj]

Solution 8 - Javascript

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))

Solution 9 - Javascript

Add an object to an array

class App extends React.Component {
  state = {
  value: ""
  };

items = [
  {
    id: 0,
    title: "first item"
  },
  {
    id: 1,
    title: "second item"
  },
  {
    id: 2,
    title: "third item"
  }
];

handleChange = e => {
  this.setState({
    value: e.target.value
  });
};

handleAddItem = () => {
  if (this.state.value === "") return;
  const item = new Object();
  item.id = this.items.length;
  item.title = this.state.value;
  this.items.push(item);
  this.setState({
    value: ""
  });

  console.log(this.items);
};

render() {
  const items = this.items.map(item => <p>{item.title}</p>);
  return (
    <>
      <label>
        <input
          value={this.state.value}
          type="text"
          onChange={this.handleChange}
        />
        <button onClick={this.handleAddItem}>Add item</button>
      </label>
      <h1>{items}</h1>
    </>
  );
}
}

ReactDOM.render(<App />, document.getElementById("root"));

Solution 10 - Javascript

let nietos = [];

function nieto(aData) {

    let o = {};

    for ( let i = 0; i < aData.length; i++ ) {
        let key = "0" + (i + 1);
        o[key] = aData[i];
    }

    nietos.push(o);
}

nieto( ["Band", "Ramones"] );
nieto( ["Style", "RockPunk"] );
nieto( ["", "", "", "Another String"] );

/* convert array of object into string json */
var jsonString = JSON.stringify(nietos);
document.write(jsonString);

Add an object into an array

Solution 11 - Javascript

Save your values in array and convert it using stringify

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

var jsonString = JSON.stringify(nietos);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpmirandaView Question on Stackoverflow
Solution 1 - Javascriptuser3589620View Answer on Stackoverflow
Solution 2 - JavascriptU.ShabaView Answer on Stackoverflow
Solution 3 - Javascriptuser889030View Answer on Stackoverflow
Solution 4 - JavascriptTowkirView Answer on Stackoverflow
Solution 5 - JavascriptLegotinView Answer on Stackoverflow
Solution 6 - JavascriptsyedmeesamaliView Answer on Stackoverflow
Solution 7 - JavascriptGassView Answer on Stackoverflow
Solution 8 - JavascriptRex SamaView Answer on Stackoverflow
Solution 9 - JavascriptArkadiusz PlumbaumView Answer on Stackoverflow
Solution 10 - JavascriptanteloveView Answer on Stackoverflow
Solution 11 - JavascriptVimalView Answer on Stackoverflow