我正在尝试将对象转换为JavaScript中的对象数组

时间:2020-10-20 12:20:02

标签: javascript arrays dictionary object ecmascript-6

这里是一个对象:

const language = {
  fluency: {
    "English": "Advanced",
    "French": "Intermediate"
  },
  read: ["English", "French"],
  speak: ["English"],
  write: ["English"]
};

我正在尝试转换为类似对象的数组:

const newLanguage = [
    {
        language: "English",
        fluency: "Advanced",
        read: true,
        speak: true,
        write: true,
    },
    {
        language: "French",
        fluency: "Intermediate",
        read: false,
        speak: false,
        write: false,
    }
]

这是我尝试过的结果:

var values = Object.entries(language).map(([k, v]) => ({[k]: v}))

其结果是:

[
  { fluency: { English: 'Advanced', French: 'Intermediate' } },
  { read: [ 'English', 'French' ] },
  { speak: [ 'English' ] },
  { write: [ 'English' ] }
]

P.S 我不是在索要代码,但是如果有人可以给我一个转换为结果的步骤,那将是一个很大的帮助! 预先感谢!

2 个答案:

答案 0 :(得分:1)

您可以利用散布运算符,将流利度与其他属性分开,然后使用.map()根据提取的流利度值构建对象数组。 Array.reduce可用于基于rest变量的属性来构建对象:

const language = {
  fluency: {
    "English": "Advanced",
    "French": "Intermediate"
  },
  read: ["English", "French"],
  speak: ["English"],
  write: ["English"]
};


let {
  fluency,
  ...rest
} = language;

let result = Object.entries(fluency).map(([lang, flue]) =>
  Object.keys(rest)
  .reduce((obj, skill) => {
    obj[skill] = rest[skill].includes(lang);
    return obj;
  }, {
    language: lang,
    fluency: flue
  })
);

console.log(result);

答案 1 :(得分:1)

您可以执行以下操作

const language = {
  fluency: {
    "English": "Advanced",
    "French": "Intermediate"
  },
  read: ["English", "French"],
  speak: ["English"],
  write: ["English"]
};

const newLanguage = []

for (const [key, value] of Object.entries(language.fluency)) {
  newLanguage.push({
        language: key,
        fluency: value,
        read: language.read.includes(key),
        speak: language.speak.includes(key),
        write: language.write.includes(key),
    });
}

console.log(newLanguage);