[英]How to create an object map of items with the most quantity from array of objects?
[英]Create object from array items
我正在尝试创建以下内容,但找不到任何成功,如果有办法,请告诉我:) 我有 2 个变量,称为 text1 和 text2,它们中的每一个都应代表 object 中的一个键和值关键将是数据变量。
In the beginning, the object will start as empty, and I need to create a function that will create that object inside the object as many times as need, it can be a case where the text will have more than 3 keys, for eg items .courses.lessons.assets.title 等。所以 function 必须是动态的。 请注意,function 必须检查该键是否已经存在,因此如果有另一个具有相同起始键的文本,它不会覆盖它(参见下面的示例)
const data1 = 'hello';
const text1 = 'lessons.first.title';
const data2 = 'hello there';
const text2 = 'lessons.first.description';
// how the end result should look like
const result = {
lessons: {
first: {
title: 'hello',
description: 'hello there',
},
},
};
谢谢!
将路径分开,删除最后一部分。 使用剩余路径循环 object。 到最后,将属性设置为值。
function setProp(obj, path, value) { var parts = path.split("."); var last = parts.pop(); var current = parts.reduce(function (acc, part) { acc[part] = acc[part] || {}; return acc[part]; }, obj); current[last] = value; } const data1 = 'hello'; const text1 = 'lessons.first.title'; const data2 = 'hello there'; const text2 = 'lessons.first.description'; var myObj = {}; setProp(myObj, text1, data1 ); setProp(myObj, text2, data2); console.log(myObj);
我是这样做的:)
const data1 = 'hello';
const text1 = 'lessons.first.title';
const data2 = 'hello there';
const text2 = 'lessons.first.description';
const res = {};
const addProp = (keys, value) => {
let temp = res;
const len = keys.split('.').length
keys.split('.').forEach((key,index)=>{
if(!temp[key]) {
temp[key] = {};
}
if(index === len - 1){
temp[key] = value;
}
temp = temp[key];
});
}
addProp(text1, data1);
addProp(text2, data2);
console.log(res);
这是我的尝试
function constructObj(obj, path, value) {
const pathArray = path.split('.');
let currentNode = obj;
for (let i = 0; i < pathArray.length; i++) {
const path = pathArray[i];
if (i === pathArray.length - 1) { // if on last element assign the value
currentNode[path] = value;
}
if (currentNode[path] === undefined) { // check if key exists
const newObj = {};
currentNode[path] = newObj;
currentNode = newObj;
} else {
currentNode = currentNode[path];
}
}
}
const result = {};
const data1 = 'hello';
const text1 = 'lessons.first.title';
constructObj(result, text1, data1);
const data2 = 'hello there';
const text2 = 'lessons.first.description';
constructObj(result, text2, data2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.