Home > database >  Append dynamic object to Array list in Javascript
Append dynamic object to Array list in Javascript

Time:12-09

I have this object:

const foo = { "userId":"250","80":"0","81":"1"};

I want to append dynamically as i expected result below but for now it is just for showing

const reqObj = {arrList:[{ "userId":"250","qId":"80","anId":"0"},{"userId":"250","qId":"81","anId":"1"}]}

CodePudding user response:

You can easily achieve the result using Object.keys and map

const foo = { userId: "250", "80": "0", "81": "1" };

const { userId, ...rest } = foo;

const reqObj = {
  arrList: Object.keys(rest).map((key) => ({
    userId,
    qId: key,
    anId: rest[key],
  })),
};

console.log(reqObj);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related