user7319004
user7319004

Reputation:

Define names for JS object properties

I have this object that looks like that

{taxi: 1, food: 1, cinema: 2, drinks: 2}

My goal is to define a name for those properties like so :

const expenseCategories = [
  { name: 'taxi', value: 1 },
  { name: 'food', value: 1 },
  { name: 'cinema', value: 2 },
  { name: 'drinks', value: 2},
];

Here is my attempt, I am nowhere near what I want to accomplish. I know it's simple but I got confused..

  var test = [];

  for (let x in expenseCategories) {
    // expenseCatAmountsObj.push(expenseCategories[x]);
    test.push( Object.defineProperty({}, {name : x}, { value: expenseCategories[x] }) )
  } 

It just returns an array inside object

[{…}, {…}, {…}, {…}]

Upvotes: 0

Views: 89

Answers (5)

VLAZ
VLAZ

Reputation: 29116

You have the steps almost right - only Object.defineProperty({}, {name : x}, { value: expenseCategories[x] }) is unneeded, since it's overly complex way of doing what you want. Instead just use an object literal:

var expenseCategories = { taxi: 1, food: 1, cinema: 2, drinks: 2 }

var test = [];

for (let x in expenseCategories) {
  test.push(
    {
      name: x,
      value: expenseCategories[x]
    }
  )
}

console.log(test)

An alternative is to iterate over Object.entries and produce an array using Array#map, destructuring, and short object initialisation syntax:

var expenseCategories = { taxi: 1, food: 1, cinema: 2, drinks: 2 }

var test = Object.entries(expenseCategories)
  .map(([name, value]) => ({name, value}))

console.log(test)

Upvotes: 0

Oliver Nybo
Oliver Nybo

Reputation: 560

You can use Object.keys

let obj = {taxi: 1, food: 1, cinema: 2, drinks: 2}
let arr = []

let keys = Object.keys(obj)

for (let i = 0; i < keys.length; i++) {
    let key = keys[i]
    arr[i] = {name: key, value: obj[key]}
}

console.log(arr)

Upvotes: 0

const temp = {taxi: 1, food: 1, cinema: 2, drinks: 2};

let expenseCategories = Object.keys(temp).map(key => ({name: key, value: temp[key]}));

Upvotes: 0

Tim VN
Tim VN

Reputation: 1193

We can loop over the keys of the object using map, which will return an array of results:

let categories = {taxi: 1, food: 1, cinema: 2, drinks: 2};

let test = Object.keys(categories).map(k => {
    return { name: k, value: categories[k] }
});

console.log(test);

Upvotes: 0

arizafar
arizafar

Reputation: 3132

You can use Object.entries and Array.prototype.map

let obj = {taxi: 1, food: 1, cinema: 2, drinks: 2}

let out = Object.entries(obj).map(([name, value]) => ({name, value}));
console.log(out)

Upvotes: 1

Related Questions