create array from object code example

Example 1: javascript object to array

//ES6 Object to Array

const numbers = {
  one: 1,
  two: 2,
};

console.log(Object.values(numbers));
// [ 1, 2 ]

console.log(Object.entries(numbers));
// [ ['one', 1], ['two', 2] ]

Example 2: javascript object to array

//Supposing fooObj to be an object

fooArray = Object.entries(fooObj);

fooArray.forEach(([key, value]) => {
  console.log(key); // 'one'
  console.log(value); // 1
})

Example 3: convert object to array javascript

var object = {'Apple':1,'Banana':8,'Pineapple':null};
//convert object keys to array
var k = Object.keys(object);
//convert object values to array
var v = Object.values(object);

Example 4: js create object from array

[
  { id: 10, color: "red" },
  { id: 20, color: "blue" },
  { id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})

//output: 
{red: 10, blue: 20, green: 30}

Example 5: how to convert object to array in javascript

const propertyValues = Object.values(person);

console.log(propertyValues);

Example 6: create array of objects javascript

let products = [
  {
    name: "chair",
    inventory: 5,
    unit_price: 45.99
  },
  {
    name: "table",
    inventory: 10,
    unit_price: 123.75
  },
  {
    name: "sofa",
    inventory: 2,
    unit_price: 399.50
  }
];
function listProducts(prods) {
  let product_names = [];
  for (let i=0; i<prods.length; i+=1) {
   product_names.push(prods[i].name);
  }
  return product_names;
}
console.log(listProducts(products));
function totalValue(prods) {
  let inventory_value = 0;
  for (let i=0; i<prods.length; i+=1) {
    inventory_value += prods[i].inventory * prods[i].unit_price;
  }
  return inventory_value;
}
console.log(totalValue(products));