javascript - 在 Javascript 中动态添加更多值
问题描述
如何在 Javascript 中定义如下的集合中动态添加更多值:
var data1 = [
{ name: 'S1', elems: [0, 1, 2] },
{ name: 'S2', elems: [1, 2, 3] },
{ name: 'S3', elems: [0, 2, 4] },
];
我想做的类似于以下内容:
(key, value) = read_a_row_from_table_of_values;
if (key is present in data1) // could be by iterating all the keys in data
{
data1[key][elems].push(value); // this is the point of concern (how to push values)
}
当我将此数据提供给另一个工具(UpSet)时,必须遵循此数据结构(以名称和元素的形式)。可以在此处找到有关此内容的详细信息。
解决方案
条目和查找将起作用
基本上
data1.find(elem => elem.name===key).elems.push(value)
如果 newValues 可能包含不在 data1 数组中的键,我们可以不做一个单行器
const data1 = [
{ name: 'S1', elems: [0, 1, 2] },
{ name: 'S2', elems: [1, 2, 3] },
{ name: 'S3', elems: [0, 2, 4] },
];
const newValues = {"S1": 4,"S2":5, "S6": 6 }
Object.entries(newValues)
.forEach(([key, value]) => {
const found = data1.find(elem => elem.name === key);
if (found) found.elems.push(value);
});
console.log(data1);
如果要合并,则需要添加缺少的键
const data1 = [
{ name: 'S1', elems: [0, 1, 2] },
{ name: 'S2', elems: [1, 2, 3] },
{ name: 'S3', elems: [0, 2, 4] },
];
const newValues = {"S1": 4,"S2":5, "S6": 6 }
Object.entries(newValues)
.forEach(([key, value]) => {
const found = data1.find(elem => elem.name === key);
if (found) found.elems.push(value);
else data1.push({name:key,elems: [value]});
})
console.log(data1);
推荐阅读
- r - 以分组观察中的重复为条件的虚拟变量
- logging - How to output last 5 minutes of a log file
- oracle - Oracle APEX values do not load on the form
- android - 从命令行构建Android应用程序(gradle)时如何限制目标平台?
- python - Convert 2D points with rotation to equirectangular projection coordinates
- html - 换行后将文本与前一个文本对齐
- html - 链接 Pulse 按钮并使表格消失
- php - 当我将我的项目上传到在线模式时,在登录 TokenMismatchException Laravel
- java - Android:当 Context 对象不允许 Parcelable 时,我应该如何在活动之间传递 ListView?
- .htaccess - 基于协议限制对目录的访问