javascript - replacing the key value with another property in array of objects
问题描述
merging array with object and returning an array with all the properties with array of object value or null
let object = {
keys: {
test1: {label: "Test_1"},
test2: {label: "Test_2"},
test3: {label: "Test_3"}
}
}
let data = [{test1: "1", test2: "2", default:"123134" }, {test1: "1", test2: "2", default:"123134"}, {test1: "1", test3: "3"}, {test3: "3"}]
I am expecting the below array of objects
let expectedArray = [{Test_1: "1", Test_2: "2", Test_3: null ,default:"123134" }, {Test_1: "1", Test_2: "2", Test_3: null, default:"123134"}, {Test_1: "1", Test_3: "3", Test_2:null }, {Test_3: "3", Test_1: null, Test_2: null}]
Tried below snippet
let res = data.map(o => {
let obj = {}
let c = Object.keys(o).forEach(aa => {
obj[object.keys[aa].label] = o[aa]
})
return obj
})
Any help appreciated
解决方案
您可以替换对象的现有键并重建新对象。
var object = { keys: { test1: { label: "Test 1" }, test2: { label: "Test 2" }, test3: { label: "Test 3" } } },
data = [{ test1: "1", test2: "2", default: "123134" }, { test1: "1", test2: "2", default: "123134" }, { test1: "1", test3: "3" }, { test3: "3" }],
templates = Object.values(object.keys).map(({ label }) => ({ [label]: null })),
result = data.map(o => Object.assign(
{},
...templates,
...Object
.entries(o)
.map(([k, v]) => ({ [k in object.keys ? object.keys[k].label : k]: v }))
));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- powerbi - 在 Power BI 中高效设置引用表
- angular - Angular Update 更新文本输入值的更有效方式
- arrays - 在数组字段中查找具有重复值的 mongo 记录
- python - 无法在 Django 的 url.py 文件中导入我的应用程序
- python - 为函数对象声明一个给定的签名
- javascript - 当我在日期选择器输入中粘贴新日期时出现日期问题(react-datepicker)
- flutter - 连续产生几个状态,但不是所有状态都被 BlocBuilder 接收
- amazon-web-services - AWS Lambda 调用 API 网关收到 500 内部服务器错误
- indexing - 重新启动 JournalArticle liferay 7 后,IndexerPostProcessor 不起作用
- typescript - 通过拖放(画布)绘制一个矩形