![](/img/trans.png)
[英]How to to put the value of a key in an object in an array based on the order of another array
[英]How to form an object based on key from another array of object?
我想根據來自另一個 object 的鍵形成一個 object 並將值設置為空字符串;
const availableList = [
{id: 1, key: 'emp_id'},
{id: 2, key: 'firstname'},
{id: 3, key: 'lastname'},
{id: 4, key: 'mobile'},
{id: 5, key: 'email'},
]
availableList .forEach(key => result [key] = availableList [key]);
預期 output:
result = {
emp_id: '',
firstname: '',
lastname: '',
mobile: '',
email: ''
}
您可以.reduce
與 object 破壞和對象的計算屬性一起使用
const availableList = [ { id: 1, key: "emp_id" }, { id: 2, key: "firstname" }, { id: 3, key: "lastname" }, { id: 4, key: "mobile" }, { id: 5, key: "email" }, ] const res = availableList.reduce( (finalObj, iteratedObj) => ({...finalObj, [iteratedObj.key]: "" }), {} ) console.log(res)
參考
如果您對 javascript、arrays 和對象不太熟悉,最好保持簡單(避免使用箭頭函數和花哨的 es6 表示法)。
一個簡單的Array#reduce
應該可以解決問題:
const availableList = [ {id: 1, key: 'emp_id'}, {id: 2, key: 'firstname'}, {id: 3, key: 'lastname'}, {id: 4, key: 'mobile'}, {id: 5, key: 'email'}, ]; var newObject = availableList.reduce(function (result, item) { result[item.key] = ''; return result; }, {}); console.log(newObject);
如果您熟悉Array#reduce
,請發表一些評論:
result
的參數是用於將數組“減少”為單個變量的值。item
的參數是每次迭代期間數組 item 的值。result
的原始值是指定為reduce
的第二個參數的值(在本例中為{}
)reduce
的 function 內部,您必須返回將在下一次迭代中作為result
參數傳入的值newObject
你有一組屬性。 因此,正如您在問題中所建議的那樣,您需要使用 forEach 來迭代所有項目。 在這種情況下,項目是對象。 因此,您只需編寫 obj.property 即可訪問它們的所有屬性。
讓我們看看如何將屬性添加到 object。 我可以:
obj.property5 = 'something'
或者我可以這樣做:
obj['property5'] = 'something'
由於您有一些不可預測的屬性名稱,因此您應該使用第二個。 這是代碼:
var secondObject = {};
availableList.forEach(function(item, index) {
secondObject[item.key] = '';
});
這是我使用Object.fromEntries()
的看法:
const availableList = [ { id: 1, key: "emp_id" }, { id: 2, key: "firstname" }, { id: 3, key: "lastname" }, { id: 4, key: "mobile" }, { id: 5, key: "email" }, ]; const result = Object.fromEntries(availableList.map((item) => [item.key, ""])) console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.