在对象数组中转换对象值?

时间:2019-11-27 10:43:15

标签: javascript arrays typescript

转换以下数组的最佳方法是什么

           [{
                "language":"de",
                "title": "test DE",
                "content": "Context DE Test",
                "summary": "Cummary DE test",
            }]

为以下格式。

            [{
                "language": { "name": "de" },
                "title": "test DE",
                "content": "Context DE Test",
                "summary": "Cummary DE test",
            }]

我需要更改对象中语言键的结构。

3 个答案:

答案 0 :(得分:1)

是的。我认为应该这样做吗?

languages.map(({ language, ...rest }) => ({
  language: { name: language },
  ...rest,
});

答案 1 :(得分:1)

尝试一下:

let array1 = [{
  "language": "fr",
  "title": "test FR",
  "content": "Context fr Test",
  "summary": "Cummary fr test",
},
{
  "language": "de",
  "title": "test DE",
  "content": "Context DE Test",
  "summary": "Cummary DE test",
}]
let res = array1.map((value, index) => {
  return { ...value, language: { name: value.language } }
})
console.log(res);

答案 2 :(得分:0)

const arr =    [{
                "language": "fr",
                "title": "test FR",
                "content": "Context fr Test",
                "summary": "Cummary fr test",
            },
            {
                "language":"de",
                "title": "test DE",
                "content": "Context DE Test",
                "summary": "Cummary DE test",
            }];

const newObj = arr.map( obj => {...obj , language : {name : obj.language}});

console.log(newObj)

像您所说的那样,使用map和散布运算符。