打字稿将对象映射到其他结构

时间:2019-03-13 09:10:54

标签: javascript typescript dictionary

我有一个具有具体结构的物体。我想创建另一个具有其他结构的东西.... map()

之类的东西
const Object: Icon = {
  Laughing: {
    iconClass: 'emoticon-3',
    name: 'Laughing :D',
    dataText: ':D',
  },
  Surprise: {
    iconClass: 'emoticon-4',
    name: "Surprise, No you di'int' :O",
    dataText: ':O',
  }
  .......
}

我想将其映射到其他对象结构:

const Object2: Type2 = {
  :D: {
    iconClass: 'emoticon-3',
    name: 'Laughing :D',
  },
  :O: {
    iconClass: 'emoticon-4',
    name: "Surprise, No you di'int' :O",
  }
  .......
}

2 个答案:

答案 0 :(得分:1)

您可以使用Object.values()reduce。使用destructuring66 BE 00000000 mov esi,0x0作为一个单独的变量,并将其余属性分配给dataText变量,如下所示:rest

{ dataText, ...rest }

按照@jo_va的建议,您还可以隐式地从const obj = { Laughing: { iconClass: 'emoticon-3', name: 'Laughing :D', dataText: ':D', }, Surprise: { iconClass: 'emoticon-4', name: "Surprise, No you di'int' :O", dataText: ':O', } } const newObj = Object.values(obj).reduce((acc, { dataText, ...rest }) => { acc[dataText] = rest; return acc }, {}) console.log(newObj)返回:

reduce

答案 1 :(得分:1)

您可以使用array#map创建对象数组,然后使用Object.assign()创建单个对象。

const obj = { Laughing: { iconClass: 'emoticon-3', name: 'Laughing :D', dataText: ':D', }, Surprise: { iconClass: 'emoticon-4', name: "Surprise, No you di'int' :O", dataText: ':O', } },
    result = Object.assign(...Object.values(obj).map(({dataText, ...o}) => ({[dataText] : o})));
console.log(result);