将对象映射到数组

时间:2019-04-16 15:44:34

标签: javascript mapping

给出这样的对象:

{
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
...
}

返回此数组的最简单方法是什么

[
   {value: "aaa", label: "Text1"},
   {value: "bbb", label: "Text2"}
]

我是否必须遍历对象?我认为Object.keys()Object.values()

可能有办法

5 个答案:

答案 0 :(得分:2)

您可以使用Object.entries将对象转换为数组。使用map循环并返回所需的对象。

let obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
}

let result = Object.entries(obj).map(([k, v]) => ({value: k,label: v.text}));

console.log(result);

答案 1 :(得分:1)

这可以帮助

const obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
};
const ans = Object.keys(obj).map(itm => ({value: itm, title: obj[itm].text}))

console.log(ans);

答案 2 :(得分:1)

您必须遍历这些键值,使用Object.entries方法来获取键值对,并使用Array#map方法来迭代并生成新数组。

let data = {"aaa":{"text":"Text1","path":"Path1","type":"Type1"},"bbb":{"text":"Text2","path":"Path2","type":"Type2"}};

let res = Object.entries(data).map(([value, { text: title }]) => ({ value, title }))

console.log(res)

答案 3 :(得分:1)

您可以使用for..in循环来迭代对象并将值推入数组中

let obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  }
}
let modObj = [];

for (let keys in obj) {
  modObj.push({
    value: keys,
    label: obj[keys].text
  })
};

console.log(modObj)

答案 4 :(得分:0)

因为没有人提到您在问题中提到过同时使用Object.keys和Object.values ...

var obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  }
};

var result = Object.keys(obj).map(function(key, i){
  return {value: key, label: Object.values(obj)[i].text}
});

console.log(result);