2017-05-31 42 views
1

我們想要做的是使用一個單一的模式創建一個新的數組(與arrObj值:爲什麼以下日誌記錄不同的值(數組循環)?

const arrObj = [{ 
    id: 1, 
    title: 'aaa' 
}, { 
    id: 2, 
    title: 'bbb', 
}] 

const schema = [{ 
    name: 'id', 
    value: '' 
}, { 
    name: 'title', 
    value: '' 
}] 

const finalArrObj = [] 

arrObj.forEach(eachArrObj => { 
    const eachArr = [...schema] // copy array without pointing to the original one 
    eachArr.forEach(field => { 
    field.value = eachArrObj[field.name] 
    console.log('1: ' , field) // correct value 
    }) 
    console.log('2: ', eachArr) // the objects are all the same 
    console.log('3: ', eachArr[0].value) // the object here is correct 
    finalArrObj.push(eachArr) 
}) 

出於某種原因,在控制檯日誌數2值記錄與同一個對象的數組。控制檯日誌數3登錄正確的對象

這究竟是爲什麼,以及如何解決它

活生生的例子:?https://codepen.io/sky790312/pen/KmOgdy

UPDATE:

期望的結果:

[{ 
    name: 'id', 
    value: '1' 
}, { 
    name: 'title', 
    value: 'aaa' 
}], 
[{ 
    name: 'id', 
    value: '2' 
}, { 
    name: 'title', 
    value: 'bbb' 
}] 
+0

您的副本是不是複製,因爲內部目標連接在一起。請添加你喜歡的東西。 –

+0

@NinaScholz請參閱我的更新。 – alex

回答

1

您可以映射新通過使用Object.assign代表schema,然後爲其分配值。

schema.map(a => Object.assign({}, a, { value: o[a.name] })) 
       ^^^^^^^^^^^^^^^^       take empty object for 
           ^      assingning values of a and 
            ^^^^^^^^^^^^^^^^^^^^ only the value of a property 

const arrObj = [{ id: 1, title: 'aaa' }, { id: 2, title: 'bbb' }], 
 
    schema = [{ name: 'id', value: '' }, { name: 'title', value: '' }], 
 
    finalArrObj = arrObj.map(o => 
 
     schema.map(a => Object.assign({}, a, { value: o[a.name] })) 
 
    ); 
 

 
console.log(finalArrObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

感謝您的回答。一個問題:如何在將值分配給新數組/對象時添加if語句? – alex

+0

你有沒有想要達到的例子? –

1

你也必須複製內部對象,更換此

const eachArr = [...schema]; 

與此

const eachArr = schema.map((e)=>{ 
    return Object.assign({}, e); 
}) 
+0

「const eachArr = [... schema]」有什麼問題;「 ?那仍然指向相同的地址? – KevinHu

+0

不,但其中的對象,他們指向相同的參考,這就是爲什麼你必須複製它們。 –

相關問題