I want to form an object based the keys from another object and set values to empty string;
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]);
Expected output:
result = {
emp_id: '',
firstname: '',
lastname: '',
mobile: '',
email: ''
}
You could use .reduce
with object destructing and object's computed property
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)
References
If you're not very familiar with javascript, arrays and objects, it's probably better to keep it simple (avoid arrow functions and fancy es6 notation).
A simple Array#reduce
should do the trick:
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);
Some comments in case you're familiar with Array#reduce
:
result
is the value you use to "reduce" the array into a single variable.item
is the value of item of array during each iteration.result
is the value specified as the second parameter of reduce
(which in this case is {}
) reduce
, you have to return the value that will be passed in as the result
parameter in the next iterationnewObject
You have an array of properties. So as you suggested in your question, you need to use a forEach to iterate all the items. The items are objects in this case. So you can access all their properties just writing obj.property.
Let's see how can I add a property to an object. I could do:
obj.property5 = 'something'
Or I could do:
obj['property5'] = 'something'
Since you have something unpredictable as the name of the property you should use the second one. Here there's the code:
var secondObject = {};
availableList.forEach(function(item, index) {
secondObject[item.key] = '';
});
Here's my take on it using 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.