我有這個樣本資料
let data = [{
id: 1,
info: [
'Optical',
'Drive'
]
},
{
id: 2,
info: [
'Paper',
'Binder'
]
}
];
我想將 data.info 中的陣列轉換為物件并分配 2 個鍵/值對,第一個鍵是帶有 data.info 值的名稱,第二個鍵是 data.info 字串的長度。結果將是這樣的:
let data = [{
id: 1,
info: [{
name: 'Optical',
length: 7
},
{
name: 'Drive',
length: 5
},
]
},
{
id: 2,
info: [{
name: 'Paper',
length: 5
},
{
name: 'Binder',
length: 6
}
]
}
];
這是我到目前為止嘗試過的
const getLength = (str) => (str.length)
const addLength = (str) => {
try {
let newObj = {};
newObj.name = str;
newObj.length = getLength(str);
return newObj;
} catch (error) {
console.log(error)
}
}
const mapedData = data.map((object) => {
object.info.map((str) => (addLength(str)))
})
然而結果是
[ undefined, undefined ]
知道如何解決嗎?
uj5u.com熱心網友回復:
要執行您需要的操作,您可以遍歷陣列,使用map()更新info每個元素內的陣列。您的原始邏輯缺少的部分是您沒有將回應設定addLength()為父物件的屬性 - 您只需執行該函式。
let data = [{id: 1,info: ['Optical','Drive']}, {id: 2,info: ['Paper','Binder']}];
data.forEach(x => {
x.info = x.info.map(y => ({
name: y,
length: y.length
}))
});
console.log(data);
uj5u.com熱心網友回復:
這很簡單
data.forEach(item => item.info = item.info.map((value) => ({name: value, length: value.length})));
uj5u.com熱心網友回復:
這應該這樣做。
const result = data.map(curr => {
// Calculate new info array
const info = curr.info.map(item => ({name: item, length: item.length}))
// Create new object from old object and use the new info
// to not mutate the original object
return {...curr, info}
}, [])
uj5u.com熱心網友回復:
const data = [{
id: 1,
info: [
'Optical',
'Drive'
]
},
{
id: 2,
info: [
'Paper',
'Binder'
]
}
];
console.log(data.map(e => ({
id: e.id,
info: e.info.map(i => ({
name: i,
length: i.length
}))
})));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513976.html
下一篇:為打字稿中的物件制作物件
