首页 > 解决方案 > 在 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)时,必须遵循此数据结构(以名称和元素的形式)。可以在此处找到有关此内容的详细信息。

标签: javascriptdictionarydata-structuresdynamic

解决方案


条目和查找将起作用

基本上

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);


推荐阅读