根據 JavaScript 中的條件將鍵值對追加到詞典陣列中?
為此,請使用 Object.assign()。以下為程式碼 −
示例
const details = {john:{'studentName':'John'},david:{'studentName':'David'},mike:{'studen tName':'Mike'},bob:{'studentName':'Bob'},carol:{'studentName':'Carol'}}, join_values = ['David', 'Carol'], output = Object.assign( {}, ...Object .keys(details) .map(key => ({[key]: { ...details[key], lastName: join_values.includes(details[key].studentName) ? 'Miller' : 'Smith' }}))) console.log(output)
要執行以上程式,你需要使用以下命令 −
node fileName.js.
輸出
此處,我的檔名是 demo157.js。這將產生以下輸出 −
PS C:\Users\Amit\JavaScript-code> node demo157.js { john: { studentName: 'John', lastName: 'Smith' }, david: { studentName: 'David', lastName: 'Miller' }, mike: { studentName: 'Mike', lastName: 'Smith' }, bob: { studentName: 'Bob', lastName: 'Smith' }, carol: { studentName: 'Carol', lastName: 'Miller' } }
廣告