简体   繁体   中英

How to change the nested array object to object depending on type in javascript

I would like to know how to change nested array object to object depending on key in javascript

I have objects obj1 and obj2 , depending on key item type change the object.


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"
  }
}


I think the reason your code is not running is because the wrong format of your objects (1 and 2). Your code is okay except the condition because trim() only works on string type so it errors on array. Try this code snippet

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

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

or cleaned up even more

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM