【问题标题】:How to change the nested array object to object depending on type in javascript如何根据javascript中的类型将嵌套数组对象更改为对象
【发布时间】:2020-12-20 03:58:12
【问题描述】:

我想知道如何根据 javascript 中的键将嵌套数组对象更改为对象

我有对象obj1obj2,根据item 的键类型更改对象。


function changeObj(obj){
  let result =  obj.reduce(function (acc, item) {
      if(item.items.trim() !== "" && item.key.trim() !== ""){
        acc[item.key] = item.items
        return acc
      }
        return acc
    }, {});
  return result;
}
let result = this.changeObj(obj2)
var obj1 = [
 { id:0, items:["SG","AU"], count: 2, key:"countries"},
 { id:1, items:["finance"], count: 3 key:"info"} 
]

var obj2 = [
  { id:0, items: "SG", key: "country"},
  { id:1, items: "details", key: "info"}
]

Expected Output:

// if items key is array
{
  fields: {
    countries: ["SG","AU",2],
    info: ["finance",3]
  }
}

//if items key is string

{
  fields: {
    country: "SG",
    info: "details"
  }
}


【问题讨论】:

  • 那么你到底是哪里出了问题?
  • @charlietfl 感谢回复,如果项目键是数组,则不起作用
  • 所以你需要另一个if(Array.isArray(item.items))的条件

标签: javascript jquery arrays object


【解决方案1】:

我认为您的代码未运行的原因是您的对象格式错误(1 和 2)。除了条件之外,您的代码还可以,因为 trim() 仅适用于字符串类型,因此它在数组上出错。试试这个代码sn-p

function changeObj(obj){
  let result =  obj.reduce(function (acc, item) {
      acc[item.key] = item.items;
      return acc;
    }, {});
  return result;
}

var obj1 = [
 { id:0, items:["SG","AU"], count: 2, key:"countries"},
 { id:1, items:["finance"], count: 3, key:"info"} 
]

var obj2 = [
  { id:0, items: "SG", key: "country"},
  { id:1, items: "details", key: "info"}
]

console.log(changeObj(obj1));

【讨论】:

    【解决方案2】:

    const changeObj = obj =>
      obj.reduce((acc, item) => {
        if (Array.isArray(item.items)) {
          acc[item.key] = [...item.items, item.count];
        } else {
          acc[item.key] = item.items;
        }
        return acc;
      }, {});
    
    var obj1 = [
      { id: 0, items: ['SG', 'AU'], count: 2, key: 'countries' },
      { id: 1, items: ['finance'], count: 3, key: 'info' }
    ];
    
    var obj2 = [
      { id: 0, items: 'SG', key: 'country' },
      { id: 1, items: 'details', key: 'info' }
    ];
    
    console.log(changeObj(obj1));
    console.log(changeObj(obj2));

    或者清理得更多

    const changeObj = obj =>
      obj.reduce((acc, { items, key, count }) => {
        Array.isArray(items) ? (acc[key] = [...items, count]) : (acc[key] = items);
    
        return acc;
      }, {});
    
    var obj1 = [
      { id: 0, items: ['SG', 'AU'], count: 2, key: 'countries' },
      { id: 1, items: ['finance'], count: 3, key: 'info' }
    ];
    
    var obj2 = [
      { id: 0, items: 'SG', key: 'country' },
      { id: 1, items: 'details', key: 'info' }
    ];
    
    console.log(changeObj(obj1));
    console.log(changeObj(obj2));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 2020-07-07
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多