简体   繁体   中英

Map Array elements and return objects

I have an array of objects like this:

var pools = [{
    dce: 3,
    lts: 2,
    name: "nift nation",
  },
  {
    dce: 1049.99,
    lts: 104.999,
    name: "NSG I.NS. Mark Select",
  },
  {
    dce: 162,
    lts: 36.157,
    name: "Shift-Team Mark Select",
  }
]

I get:

[
  {
    "nift_nation": [
      {
        "nift_nationDollars": ""
      },
      {
        "nift_nationUnits": ""
      },
      {
        "nift_nationPercentage": ""
      }
    ]
  },
  {
    "NSG_I$NS$_Mark_Select": [
      {
        "NSG_I$NS$_Mark_SelectDollars": ""
      },
      {
        "NSG_I$NS$_Mark_SelectUnits": ""
      },
      {
        "NSG_I$NS$_Mark_SelectPercentage": ""
      }
    ]
  },
  {
    "Shift__Team_Mark_Select": [
      {
        "Shift__Team_Mark_SelectDollars": ""
      },
      {
        "Shift__Team_Mark_SelectUnits": ""
      },
      {
        "Shift__Team_Mark_SelectPercentage": ""
      }
    ]
  }
]

 var pools = [{ dce: 3, lts: 2, name: "nift nation", }, { dce: 1049.99, lts: 104.999, name: "NSG I.NS. Mark Select", }, { dce: 162, lts: 36.157, name: "Shift-Team Mark Select", } ] var getFieldSuffix = function(rowFieldCount) { switch (rowFieldCount) { case 0: return 'Dollars'; case 1: return 'Units'; case 2: return 'Percentage'; default: return } }; var replacementMap = { single_space: '_', dot: '$', hyphen: '__', }; var replacer = function(str) { return str.replace(/[ .-]/g, l => { if (l == ".") return replacementMap["dot"]; if (l == " ") return replacementMap["single_space"]; return replacementMap["hyphen"]; }); }; var arrObj = pools.map(function(pool) { return Object.assign({ [replacer(pool.name)]: ['Dollars', 'Units', 'Percentage'].map(function(suffix, index) { return { [replacer(pool.name) + getFieldSuffix(index % 3)]: '' } }) }) }) console.log(arrObj) 

I want:

{
  {
    "nift_nation": {
      "nift_nationDollars": "",
      "nift_nationUnits": "",
      "nift_nationPercentage": "",
    }
  },
  {
    "NSG_I$NS$_Mark_Select": {
      "NSG_I$NS$_Mark_SelectDollars": "",
      "NSG_I$NS$_Mark_SelectUnits": "",
      "NSG_I$NS$_Mark_SelectPercentage": "",
    }
  },
  {
    "Shift__Team_Mark_Select": {
      "Shift__Team_Mark_SelectDollars": "",
      "Shift__Team_Mark_SelectUnits": "",
      "Shift__Team_Mark_SelectPercentage": "",
    }
  } 
}

You can use the reduce() method instead of map().

Like so:

return Object.assign({
    [replacer(pool.name)]: ['Dollars', 'Units', 'Percentage'].reduce(function(acc, suffix, index) { 
        acc[replacer(pool.name) + getFieldSuffix(index % 3)] = ''; 
        return acc;
     }, {})
  })

The difference is that when you use map, you return an array. Whereas with reduce you return whatever the result of your accumulator is, in this case it is an object that then gets patched into your parent object.

This can then be applied to your entire transform like so:

var arrObj = pools.reduce(function(acc, pool) {
  acc[replacer(pool.name)] = ['Dollars', 'Units', 'Percentage'].reduce(function(acc, suffix, index) { 
        acc[replacer(pool.name) + getFieldSuffix(index % 3)] = ''; 
        return acc;
     }, {});
   return acc;
}, {})

There you go, you were close

var pools = [{
    dce: 3,
    lts: 2,
    name: "nift nation",
  },
  {
    dce: 1049.99,
    lts: 104.999,
    name: "NSG I.NS. Mark Select",
  },
  {
    dce: 162,
    lts: 36.157,
    name: "Shift-Team Mark Select",
  }
]

var getFieldSuffix = function(rowFieldCount) {
  switch (rowFieldCount) {
    case 0:
      return 'Dollars';
    case 1:
      return 'Units';
    case 2:
      return 'Percentage';
    default:
      return
  }
};

var replacementMap = {
  single_space: '_',
  dot: '$',
  hyphen: '__',
};

var replacer = function(str) {
  return str.replace(/[ .-]/g, l => {
    if (l == ".") return replacementMap["dot"];
    if (l == " ") return replacementMap["single_space"];
    return replacementMap["hyphen"];
  });
};

var arrObj = Object.assign(...pools.map((pool) => {
  return {
    [replacer(pool.name)]: Object.assign(...['Dollars', 'Units', 'Percentage'].map(function(suffix, index) {
      return {
        [replacer(pool.name) + getFieldSuffix(index % 3)]: ''
      }
    }))
  }
}))

console.log(arrObj)

Best (and obvious) solution: Refactor your code in a way that it returns what you want (others already provided approaches).

But, for the sake of more general solution (in case you only had the result you reported and not the original data), you can transform it according your specifications:

const formattedResult = Object.assign.apply(null, arrObj.map(function(o){
    let k=Object.keys(o)[0];
    return {[k]:Object.assign.apply(null, o[k])};
}));
console.log(formattedResult);

 var pools = [{ dce: 3, lts: 2, name: "nift nation", }, { dce: 1049.99, lts: 104.999, name: "NSG I.NS. Mark Select", }, { dce: 162, lts: 36.157, name: "Shift-Team Mark Select", } ] var getFieldSuffix = function(rowFieldCount) { switch (rowFieldCount) { case 0: return 'Dollars'; case 1: return 'Units'; case 2: return 'Percentage'; default: return } }; var replacementMap = { single_space: '_', dot: '$', hyphen: '__', }; var replacer = function(str) { return str.replace(/[ .-]/g, l => { if (l == ".") return replacementMap["dot"]; if (l == " ") return replacementMap["single_space"]; return replacementMap["hyphen"]; }); }; var arrObj = pools.map(function(pool) { const obj = {}; ['Dollars', 'Units', 'Percentage'].forEach(function(suffix, index) { obj[replacer(pool.name) + getFieldSuffix(index % 3)] = '' }) return Object.assign({ [replacer(pool.name)]: obj }) }) console.log(arrObj) 

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