1

Say i have an object like this..

const obj = {
  streaming_tile_x: 608,
  streaming_tile_z: 608,
  global_total_mesh_count: 9776,
  global_total_asset_count: 17831,
  global_total_texture_count: 64055,
  global_total_entity_count: 0,
  global_total_shader_count: 9776,
}

How can i convert it to an array of objects like this...

const results = [
    { 
        name: "streaming_tile_x", 
        value: 608 
    },
    { 
        name: "streaming_tile_z", 
        value: 608 
    },
    { 
        name: "global_total_mesh_count", 
        value: 9776 
    },
    { 
        name: "global_total_asset_count", 
        value: 17831 
    },
    { 
        name: "global_total_texture_count", 
        value: 64055 
    },
    { 
        name: "global_total_entity_count", 
        value: 0 
    },
    { 
        name: "global_total_shader_count", 
        value: 9776 
    },
]

4 Answers 4

1
Object.keys(obj).map(key => ({name: key, value: obj[key]}))
Sign up to request clarification or add additional context in comments.

1 Comment

great thanks. ill mark as answer when i can
1

Use Object.entries() with map() and array destructuring:

const obj = {
  streaming_tile_x: 608,
  streaming_tile_z: 608,
  global_total_mesh_count: 9776,
  global_total_asset_count: 17831,
  global_total_texture_count: 64055,
  global_total_entity_count: 0,
  global_total_shader_count: 9776,
};

const result = Object.entries(obj).map(([name, value]) => ({name, value}));

console.log(result);

Comments

0

You can use a simple for in loop to make this new array

const obj = {
  streaming_tile_x: 608,
  streaming_tile_z: 608,
  global_total_mesh_count: 9776,
  global_total_asset_count: 17831,
  global_total_texture_count: 64055,
  global_total_entity_count: 0,
  global_total_shader_count: 9776,
}

let array = []

for (let object in obj) {
  array.push({
    name: object,
    value: obj[object]
  })
}

console.log(array)

Comments

0

First catch the object keys then iterate over there.

obj = {
  streaming_tile_x: 608,
  streaming_tile_z: 608,
  global_total_mesh_count: 9776,
  global_total_asset_count: 17831,
  global_total_texture_count: 64055,
  global_total_entity_count: 0,
  global_total_shader_count: 9776,
}

n = Object.keys(obj).map((o) => {
  return {
    name: o,
    value: obj[o]
  }
})

console.log('n', n);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.