How to Push Value Pair into Object Using Method

How to push an array of object as key value pair into an array

You are using the key from the JSON as the index in your array. Try this.

Object.keys(this.lineItem.rows).forEach(key => {
var obj = {};
obj[key] = this.lineItem.rows[key];
this.resultArray.push(obj);
});

how to push value pair into object using method?

You need to check if the key exist, and then either push or assign the value, like this, where you use the bracket notation, this.rosterList[grade], to set the key.

Note, when assign with Arry.push(value) you will get the length of the array, not the array itself.

Stack snippet

class School{    constructor(){      this.rosterList = {};    }    roster(){        return this.rosterList;    }    add(name,grade){        this.rosterList[grade] ?          this.rosterList[grade].push(name) :          this.rosterList[grade] = [name];    }}
let a = new School;a.add('tom', 2)a.add('amy', 2)console.log(a.roster());

Adding elements to object

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
"[{"a":1},{"a":2}]"

How to push object literals as key-value pairs to array?

You can achieve the required result using plain JS:

Object.keys(myObject).map(key => ({[key]: myObject[key]}));

This approach uses computed property names of ES2015.

As suggested in comments, you can use Object.entries as well:

Object.entries(myObject).map(([p, v]) => ({[p]: v}))

If you want to use lodash anyway, you should surround key with square brackets:

const newArray = _.map(myObject, (value, key) => ({[key], value}))

Javascript Object push() function

push() is for arrays, not objects, so use the right data structure.

var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
if ( data[index].Status == "Valid" ) {
tempData.push( data );
}
}
data = tempData;


Related Topics



Leave a reply



Submit