Home > Blockchain >  loop throught an object and return a array of object
loop throught an object and return a array of object

Time:06-24

How can I loop over this object(data) and return a an array of object (output) just like this. basically with these specific properties and value

data = {
"model-10389": 164703,
"model-10388": 164704,
"model-10387": 164705,
}


const output  = [
{
  modelId : 10389,
 id : 164703
},
{
  modelId : 10388,
  id : 164704
},
{
  modelId : 10387,
  id : 164705
},
]

this is what I have now

Object.keys(data).map(function(key, index) {
 console.log(data[key])
});

or this

for (const property in data) {
console.log(`${property}: ${data[property]}`);
}

CodePudding user response:

Split the problem up into small parts:

  1. Get all "entries" of the source object.
  2. These entries need to be transformed, we can use Array.map for that
  3. Every entry is an [key, value] array, we can use destructuring in the .map for easy access.
  4. For the modelId, we need to .split the key, and get the part behind the -, then parse it as a number.
  5. The id is just the value.

const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };

const result = Object.entries(data)
  .map(([key, value]) => ({
    modelId: parseInt(key.split('-')[1], 10),
    id: value
  }));

console.log(result);

A slightly faster alternative to the split, id to use a regex to extract ids:

modelId: parseInt(key.match(/\d /)[0], 10),

CodePudding user response:

I'd use Object.entries with object destructuring, short object literal syntax and unary for conversion to number:

const data = {"model-10389": 164703,  "model-10388": 164704,  "model-10387": 164705};

const output = Object.entries(data).map(([key, id]) => ({
    modelId:  key.split("-").pop(),
    id
}));

console.log(output);

CodePudding user response:

If the key(model-*) in data doesn't change, then you can use substring() with the index.

const data = {
  "model-10389": 164703,
  "model-10388": 164704,
  "model-10387": 164705
}

const result = Object.entries(data)
                .map(([key, value]) => ({
                  modelId:  key.substring(6),
                  id: value
                }));
                
console.log(result)

  • Related