如題,有一個長得像
const words = [{mediaType:[{name: "a", y: 1},{name: "b", y: 2}]},{mediaType:[{name: "c", y: 14},{name: "d", y: 72}]}];
這樣結構的陣列
我想要把 mediaType 替換成
const name =['data1','data2']
也就是會變成
const words = [{data1:[{name: "a", y: 1},{name: "b", y: 2}]},{data2:[{name: "c", y: 14},{name: "d", y: 72}]}];
請問該怎麼做,我卡了一個下午了救救我嗚嗚嗚
const words = [
{
mediaType: [
{ name: "a", y: 1 },
{ name: "b", y: 2 },
],
},
{
mediaType: [
{ name: "c", y: 14 },
{ name: "d", y: 72 },
],
},
];
const newWords = words.map((word, index) => ({
[`data${index + 1}`]: word.mediaType,
}));
Note:此方法只能創新陣列哦,不然就是要把原本的words陣列遍歷,但會比較麻煩,如果堅持要同一個變數,請參考以下
words.forEach((word, index) => {
words[index] = { [`data${index + 1}`]: word.mediaType };
});
我是要用物件新增元件 還是轉成 json 在處理會比較好
const objWords = {};
words.forEach((word, index) => {
objWords[`data${index + 1}`] = word.mediaType;
});
那就確定一定要用新的變數哦,原本 words
已經定義成陣列了,再怎麼魔改都不可能變物件