将简单对象转换为复杂数组

时间:2018-02-12 12:28:53

标签: javascript arrays object

我一直在尝试将以下对象映射到以下数组,我对map / sort和reduce很新。是否有可能获得想要的结果?

发件人:

{
  boxer: Array []
  brabancon: Array []
  briard: Array []
  bulldog: Array [ "boston", "french" ]
}

[
  {dogBreed: 'boxer'},
  {dogBree: 'brabancon'},
  {dogBree: 'briard'},
  {dogBree: 'bulldog (boston)'},
  {dogBree: 'bulldog (french)'}
]

5 个答案:

答案 0 :(得分:1)

尝试此代码示例(旧方式):

var res = []

var obj = {
  boxer: [],
  brabancon: [],
  briard: [],
  bulldog: [ "boston", "french" ]
}

for (var key in obj) {
   if (!obj[key].length) {
       res.push({
          dogBreed: key
       })
   } else {
       for (var i = 0; i < obj[key].length; i++) {
           res.push({
              dogBreed: key + ' (' + obj[key][i] + ')'
           })
       }
   }
}
console.log(res)

或使用+ ES2015 with reduce或map

const obj = {
  boxer: [],
  brabancon: [],
  briard: [],
  bulldog: [ "boston", "french" ]
}

result = Object.keys(obj).reduce((arr, key) => {
   if (obj[key].length) {
   	obj[key].forEach((item) => {arr.push({dogBreed: `${key} (${item})`})})
   } else {
   	arr.push({dogBreed: key})
   }
   return arr;
}, [])
console.log(result)

有关详细信息,这video帮助我了解了reduce。

答案 1 :(得分:1)

试试这个:

brew install watchman

const input = { boxer: [], brabancon: [], briard: [], bulldog: ['boston', 'french'], }; console.log([].concat(...Object.entries(input).map(([key, value]) => (value.length > 0 ? value : ['']).map(x => ({ dogBreed: key + (x ? ` (${x})` : '') })) )));部分用于展平数组,即将对象数组数组转换为对象数组。

有关详细说明,请参阅文档:Object.entries()map()arrow functionstemplate literalsdestructuring

答案 2 :(得分:1)

使用map不是一个好方法,因为在某些情况下,每个键需要多个元素。您可以使用reduce代替。这是一个例子。

var org = {
  boxer: [],
  brabancon: [],
  briard: [],
  bulldog: [ "boston", "french" ]
}

var arr = Object.keys(org).reduce((acc, key) => {
  if(org[key].length){
    org[key].forEach(v => acc.push({dogBreed: `${key} (${v})`}));
  }else{
    acc.push({dogBreed: key});
  }
  return acc;
}, []);
console.log(arr);

答案 3 :(得分:0)

使用Object.keys将对象的键获取到数组中。然后遍历数组并将每个对象推送到新数组中。

public ref class ClassA
{
public:
.
.
.
bool methodA();
bool methodB();
}

请看链接: https://jsfiddle.net/vrfj6o05/2/

答案 4 :(得分:0)

let testing = {
  boxer: [],
  brabancon: [],
  briard: [],
  bulldog: [ "boston", "french" ]
}

function convertToObjectArray(testing, objKey) {
  let array = [];
  Object.keys(testing).forEach(function(el) {
    if(testing[el] && testing[el].length > 0) {
      testing[el].forEach(function(e) {
        let obj = {};
        obj[objKey] = el + ' (' + e + ')';
        array.push(obj);
      });
    }
    else {
      let obj = {};
      obj[objKey] = el;
      array.push(obj);
    }
  });
  return array;
}

let finalArray = convertToObjectArray(testing, 'dogBreed');
console.log(finalArray);