映射的对象版本

时间:2018-09-20 23:08:56

标签: javascript reactjs object

  

重复的:map function for objects (instead of arrays)

我该如何映射或迭代其中值是另一个对象的对象,

[{
    "id":2,
    "name":"Jane Smith",
    "position":"Cook",
    "applied":"02/08/16",
    "experience":4,
    "availability":{
        "M":1,
        "T":1,
        "W":1,
        "Th":1,
        "F":0,
        "S":0,
        "Su":0
    },
    "questions": [{
        "text":"Have you ever been convicted of a felony?",
        "answer":"Yes"
    }]
},
...(2 other objects with the same format)....
]

我需要访问availability对象

3 个答案:

答案 0 :(得分:0)

我假设您想要一个可用性对象列表。

const availabilityObjects = objects.map(object => object.availability)

会这样做。代码段如下:

const objects =  [{
 		"id": 2,
 		"name": "Jane Smith",
 		"position": "Cook",
 		"applied": "02/08/16",
 		"experience": 4,
 		"availability": {
 			"M": 1,
 			"T": 1,
 			"W": 1,
 			"Th": 1,
 			"F": 0,
 			"S": 0,
 			"Su": 0
 		},
 		"questions": [{
 			"text": "Have you ever been convicted of a felony?",
 			"answer": "Yes"
 		}]
 	},
 	{
 		"id": 2,
 		"name": "Jane Smith",
 		"position": "Cook",
 		"applied": "02/08/16",
 		"experience": 4,
 		"availability": {
 			"M": 1,
 			"T": 1,
 			"W": 1,
 			"Th": 1,
 			"F": 0,
 			"S": 0,
 			"Su": 0
 		},
 		"questions": [{
 			"text": "Have you ever been convicted of a felony?",
 			"answer": "Yes"
 		}]
 	},
 	{
 		"id": 2,
 		"name": "Jane Smith",
 		"position": "Cook",
 		"applied": "02/08/16",
 		"experience": 4,
 		"availability": {
 			"M": 1,
 			"T": 1,
 			"W": 1,
 			"Th": 1,
 			"F": 0,
 			"S": 0,
 			"Su": 0
 		},
 		"questions": [{
 			"text": "Have you ever been convicted of a felony?",
 			"answer": "Yes"
 		}]
 	}
 ]
 
 console.log(objects.map(object => object.availability))

答案 1 :(得分:0)

请注意,不能保证对象键的顺序,因此没有完全一致的方法可以迭代它们。但是,您可以使用for...in语句来迭代对象的可枚举属性。您可以使用它基本上遍历它们的对象的键/值对,并对其进行操作。

const availability = {
    "M":1,
    "T":1,
    "W":1,
    "Th":1,
    "F":0,
    "S":0,
    "Su":0
};
for (const key in availability) {
    console.log(key, availability[key]);
}

// Output:
/*
  M 1
  T 1
  W 1
  Th 1
  F 0
  S 0
  Su 0
*/

由于目前尚不清楚您要如何使用数据,因此我无法提供更多详细信息,但这应该可以帮助您入门。

答案 2 :(得分:0)

对象的map()等效项是Object.keys()Object.entries() 这是ES7中引入的功能

    const data = [{
    "id":2,
    "name":"Jane Smith",
    "position":"Cook",
    "applied":"02/08/16",
    "experience":4,
    "availability":{
        "M":1,
        "T":1,
        "W":1,
        "Th":1,
        "F":0,
        "S":0,
        "Su":0
    },
    "questions": [{
        "text":"Have you ever been convicted of a felony?",
        "answer":"Yes"
    }]
}
 ]

    console.log(Object.entries(data[0].availability));
    console.log(Object.keys(data[0].availability));

在这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys检查 对于数据,如果您有多个对象,则可以首先使用array.map()遍历数组,然后在Object.entries()内使用map()