简体   繁体   中英

Javascript want to push objects into array

I want to push objects into array (mainArr) in JS. Below is my code:

var object = {1: 15, 2: 30};
var mainArr = ['settingsData'];

var values = Object.values(object);
var final = [];
var counter = 0;
var portion = {};

for (var key in object) {
  if (counter !== 0 && counter % 1 === 0) {
    final.push(portion);
    mainArr.push(portion)
    portion = {};
  }
  portion[key] = values[counter];
  counter++
}
final.push(portion);
mainArr.push(portion)
console.log(mainArr)

I see the output in the console like: ["settingsData", {1: 15}, {2: 30}]

But I want the output like:

{ "settingsData":[{"1":"4"},{"2":"3"}] }

You could map single key/value pairs as new entry.

 var object = { 1: 15, 2: 30 }, settingData = Object.entries(object).map(keyValue => Object.fromEntries([keyValue])), result = { settingData }; console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Answer has already been accepted, but OP did request i put my comment as an answer.

This simplifies your approach drastically:

// Create a new object to start with: 
let main = {"settingsData": []};

// Then push to the inner array:
main.settingsData.push({1:15});

If I understood it correctly, this would work:

var object = {1: 15, 2: 30};
var mainArr = {'settingsData': []};

var values = Object.values(object);
var final = [];
var counter = 0;
var portion = {};

for (var key in object) {
  if (counter !== 0 && counter % 1 === 0) {
    final.push(portion);
    mainArr.push(portion)
    portion = {};
  }
  portion[key] = values[counter];
  counter++
}
final.push(portion);
mainArr.settingsData.push(portion)
console.log(mainArr)

EDIT: (Explanaition added as asked in comments)

What you were doing is push each element into the already existing array containing ['settingsData'] . But what you were doing was to add items to the array located in the key settingsData .

So the changes were to set mainArr as an object containing field settingsData with an empty array as value, this is done on const mainArr = { settingData: []}

Then the push was done over the array contained in settingsData with mainArr.settingsData.push(newValue) .

If you need further explanaition just ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM