61

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?

Gass
  • 4,098
  • 2
  • 13
  • 27
pmiranda
  • 6,162
  • 9
  • 51
  • 114
  • 1
    `"02": "Ramones"` I assume? Also, in that case, why the array? Sounds like you want to construct a simple object – Madara's Ghost Oct 25 '16 at 21:37
  • Edited, yes, sorry. I will use that array with another function to create an XML file. Large history. – pmiranda Oct 25 '16 at 21:41
  • So the array will always have exactly one element? The numbered object? – Madara's Ghost Oct 25 '16 at 21:43
  • No, will have more objects: nietos = [{"01":"Band", "02": "Ramones"}, {"01":"Style", "02": "RockPunk"}, {"01": "", "02": "", "03" : "Another String"}] different objects with different lengths. – pmiranda Oct 25 '16 at 21:47

11 Answers11

111

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);
  • Why do you need to use "01" as the key? What if I wanted to use `nieto.label` as the key? – Amon Feb 04 '22 at 18:22
43

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.

henser
  • 3,249
  • 2
  • 35
  • 45
U.Shaba
  • 431
  • 4
  • 6
  • Why do you need to use "01" as the key? What if I wanted to use nieto.label as the key? – Amon Feb 04 '22 at 18:22
  • @Amon 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. – U.Shaba Feb 07 '22 at 16:08
11

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);
Community
  • 1
  • 1
user889030
  • 3,643
  • 2
  • 41
  • 50
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";
Towkir
  • 3,811
  • 2
  • 20
  • 38
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"}
Legotin
  • 1,936
  • 1
  • 16
  • 27
0

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

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]
Gass
  • 4,098
  • 2
  • 13
  • 27
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))
-1

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"));
  • @JacobPenney, I don't think you mean for author to add a question, but context around the proposed solution. ;) – ChrisMM Dec 15 '19 at 17:33
-1

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

antelove
  • 2,612
  • 20
  • 19
-2

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);
Vimal
  • 1
  • 1
    Hello and welcome to StackOverflow! According to the original question, the OP did not need to convert their array to a string. Why do you do so in your answer? Furthermore, with your return being placed above, your stringify code is never executed. – Ad5001 Jul 28 '21 at 10:04