![](/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.