[英]Getting key of each object inside array of objects into an array: Javascript
I have an object with the following format 我有以下格式的对象
var obj = [{
"a": 1
}, {
"b": 2
}, {
"c": 3
}];
Would want to fetch only keys out of each object inside this array of objects into a new array 想要只从该对象数组内的每个对象中提取键到新数组中
Something like this: ["a","b","c"]
像这样的东西:
["a","b","c"]
Have tried the following but it is not working : 尝试了以下方法,但是它不起作用:
var obj = [{ "a": 1 }, { "b": 2 }, { "c": 3 }]; let result = obj.map (({ val }) => val) console.log(result);
Merge to a single object by spreading into Object.assign()
, and then get the keys: 通过扩展到
Object.assign()
合并到单个对象,然后获取键:
var obj = [{"a":1},{"b":2},{"c":3}]; const result = Object.keys(Object.assign({}, ...obj)); console.log(result);
Or use Array.flatMap()
with Object.keys()
: 或者将
Array.flatMap()
与Object.keys()
:
var obj = [{"a":1},{"b":2},{"c":3}]; const result = obj.flatMap(Object.keys); console.log(result);
I'd .map
and extract the first item in the Object.keys
of the object being iterated over: 我将
.map
并提取要迭代的对象的Object.keys
中的第一项:
var obj = [{ "a": 1 }, { "b": 2 }, { "c": 3 }]; const result = obj.map(inner => Object.keys(inner)[0]); console.log(result);
You can make use of Object.assign
and spread(...)
operator to solve this issue 您可以使用
Object.assign
和spread(...)
运算符来解决此问题
var mainObj = [{"a":1},{"b":2},{"c":3},{"23":1},{"32b":2},{"232c":3}]; const allKeys = Object.keys(Object.assign({}, ...mainObj)); console.log(allKeys);
You can simply use .map() to open the array and then use Object.keys to return the key from the object. 您可以简单地使用.map()打开数组,然后使用Object.keys从对象返回键。 Please refer the example I have made.I hope it helps
请参考我所做的示例。希望对您有所帮助
https://www.w3schools.com/code/tryit.asp?filename=G66AEBM9ZJCD https://www.w3schools.com/code/tryit.asp?filename=G66AEBM9ZJCD
let object1 = [{a:1,b:2,c:3}]
let final = object1.map(function(object){
return Object.keys(object)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.