如何将带有对象的数组中的数据动态添加到嵌套数组中?

How to dynamically add data from an array with objects to a nested array?

我有这组动态获取的数据- This is the data I dynamically get

我的问题是如何从键、模式和标签中获取值并将它们放入这样的嵌套对象中 - how should the nested object look like.

我当前的密码是

let mergeTagsObj = {};  
  const merg = function(arr){
    const propertyDataMap = arr.map(x => x.key);
    propertyDataMap.forEach(x => {
      mergeTagsObj[x] = {} 
    });
    console.log(mergeTagsObj);
    // console.log(object);
  };
  merg(displayArr)

displayArr 有我动态获取的数据,我映射每个数据以获取密钥,这样我就可以给对象 属性 一个名称。但之后我需要得到另外 2 个(图案和标签)并将其放入 mergeTagsObj;

ex: mergeTagsObj = {
firstName:{
name:{label}
value:{pattern}
},
...
};

不是最优雅的解决方案,但我认为这应该可行。不需要先创建键数组,你可以遍历对象的 arr。

  const merg = function(arr){
    arr.forEach(x => {
      mergeTagsObj[x.key] = {};
      mergeTagsObj[x.key]['name'] = x.label;
      mergeTagsObj[x.key]['value'] = x.pattern
    });
    console.log(mergeTagsObj);
    // console.log(object);
  };
// Given
const data = [
  {key: "firstName", pattern: "{{firstName}}", label: "First Name"},
  {key: "unsubscribeLink", pattern: "{{unsubscribeLink}}", label: "Unsubscribe Link"}
];

const tagsObject = data.reduce((obj, item) => {
  const key = item.key;
  const name = item.label;
  let value = item.pattern;
  if (key === 'unsubscribeLink') value = '<a href="{{unsubscribeLink}}">Unsubscribe</a>';

  return {...obj, [key]: {name, value}};
}, {});

console.log(tagsObject);

您可以在 forEach 中添加模式和标签,以及您可能需要转换数据的任何其他逻辑。

const data = [{key: 'firstName', pattern: "{{firstName}}", label: "First Name"}, 
              {key: 'lastName', pattern: "{{lastName}}", label: "Last Name"},
              {key: 'unsubscribeLink', pattern: "{{unsubscribeLink}}", label: "Unsubscribe Link"}
             ]

const transformDataToTagsObject = (dData) => {
  
  const dynamicData = {};

  dData.forEach((currentData, index) => {
    
    const currentKey = currentData.key
    const name = currentData.label
    let value = currentData.pattern
    
    if(currentData.key === 'unsubscribeLink'){
      value = `<a href='${value}'>Unsubscribe</a>`
     }
    
     dynamicData[currentKey] = {
      name,
      value
     }
    
  })
  
  const tagsObject = {
    tags: dynamicData
  }
   return tagsObject;
}

const finalResults = transformDataToTagsObject(data)

console.log(finalResults)