从嵌套对象创建对象数组

时间:2019-05-20 05:11:38

标签: javascript arrays loops object nested

我有一个嵌套对象'empData'。 我需要遍历对象中的每个键并返回对象数组。 我的对象'empData'中的每个键再次都是一个对象。

现在,我需要返回一个对象数组:

预期输出:

[{
 "team": "AUS",
 "name": "John"
}, {
 "team": "CAN",
 "name": "Steve"
}, {
 "team": "IND",
 "name": "Robbie"
}, {
 "team": "IRE",
 "name": "James"
}, {
 "team": "USA",
 "name": "Austin"
}];

我的代码:

function getData() {
 const empData = {
  "AUS": {
   "isRetired": true,
   "name": "John"
  },
  "CAN": {
   "name": "Steve"
  },
  "IND": {
   "name": "Robbie"
  },
  "IRE": {
   "name": "James"
  },
  "USA": {
   "name": "Austin"
  }
 };
 Object.keys(empData).map(function(eachKey) {
  const obj = {
   team: eachKey,
   name: eachKey.name
  };
  console.log(obj);
  return obj;
 });
}
<button onclick="getData()">Get Data</button>

有人可以帮我吗?

4 个答案:

答案 0 :(得分:4)

更改name: eachKey.name

 name: empData[eachKey].name



function getData() {
 const empData = {
  "AUS": {
   "isRetired": true,
   "name": "John"
  },
  "CAN": {
   "name": "Steve"
  },
  "IND": {
   "name": "Robbie"
  },
  "IRE": {
   "name": "James"
  },
  "USA": {
   "name": "Austin"
  }
 };
 Object.keys(empData).map(function(eachKey) {
  const obj = {
   team: eachKey,
   name: empData[eachKey].name
  };
  console.log(obj);
  return obj;
 });
}

答案 1 :(得分:2)

您可以使用Object.entries将对象转换为数组。使用map遍历数组。

Object.entries第一个元素是键,第二个元素是值。

const empData = {
  "AUS": {
    "isRetired": true,
    "name": "John"
  },
  "CAN": {
    "name": "Steve"
  },
  "IND": {
    "name": "Robbie"
  },
  "IRE": {
    "name": "James"
  },
  "USA": {
    "name": "Austin"
  }
};

var result = Object.entries(empData).map(([team, {name}]) => ({team,name}));

console.log(result);

答案 2 :(得分:2)

.map Object.entries代替,因此您可以一次提取密钥(获取team和值(以便获取name):

const empData = {
  "AUS": {
    "isRetired": true,
    "name": "John"
  },
  "CAN": {
    "name": "Steve"
  },
  "IND": {
    "name": "Robbie"
  },
  "IRE": {
    "name": "James"
  },
  "USA": {
    "name": "Austin"
  }
};
const getData = () => {
  const result = Object.entries(empData).map(([team, { name }]) => ({
    team,
    name
  }));
  console.log(result);
};
<button onclick="getData()">Get Data</button>

答案 3 :(得分:1)

您可以使用for..in遍历对象,并使用相关的键和值创建一个新对象,然后推入另一个数组

function getData() {
  const empData = {
    "AUS": {
      "isRetired": true,
      "name": "John"
    },
    "CAN": {
      "name": "Steve"
    },
    "IND": {
      "name": "Robbie"
    },
    "IRE": {
      "name": "James"
    },
    "USA": {
      "name": "Austin"
    }
  };

  let newData = [];
  for (let keys in empData) {
    newData.push({
      team: keys,
      name: empData[keys].name
    })
  }
  console.log(newData)
}

getData()