定义JS对象属性的名称

时间:2019-05-20 11:37:54

标签: javascript

我有一个看起来像这样的对象

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

我的目标是为这些属性定义一个名称,如下所示:

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

这是我的尝试,我距离要完成的目标还很遥远。我知道这很简单,但是我很困惑。

  var test = [];

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

它只是在对象内部返回一个数组

  

[{...},{...},{...},{...}]

5 个答案:

答案 0 :(得分:2)

您可以使用Object.entriesArray.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)

答案 1 :(得分:0)

我们可以使用map遍历对象的键,这将返回结果数组:

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);

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

您几乎可以正确执行所有步骤-不需要Object.defineProperty({}, {name : x}, { value: expenseCategories[x] }),因为这是完成所需操作的过于复杂的方法。而是只使用对象文字:

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)

另一种方法是遍历Object.entries并使用Array#mapdestructuringshort 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)

答案 4 :(得分:0)

您可以使用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)