JavaScript에서 객체 {}를 키-값 쌍의 배열 []으로 변환하는 방법
다음과 같은 객체를 변환하고 싶습니다.
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
다음과 같이 키-값 쌍의 배열로
[[1,5],[2,7],[3,0],[4,0]...].
JavaScript에서 객체를 키-값 쌍의 배열로 변환하려면 어떻게해야합니까?
당신은 이것을 Object.keys()
하고 map()
할 수 있습니다
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map(function(key) {
return [Number(key), obj[key]];
});
console.log(result);
가장 좋은 방법은 :
var obj ={"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
Object.entries(obj);
entries
여기에 표시된대로 호출 하면 [key, value]
요청자가 요청한대로 쌍 을 반환 합니다.
또는을 호출하면 Object.values(obj)
값만 반환됩니다.
Object.entries()
요소가[key, value]
직접 찾을 수 있는 열거 가능한 속성 쌍에 해당하는 배열 인 배열을 반환합니다object
. 속성의 순서는 객체의 속성 값을 수동으로 반복하여 주어진 순서와 동일합니다.-https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Description
이 Object.entries
함수는 키가 숫자 대신 문자열 인 것을 제외하고는 거의 정확한 결과를 반환합니다.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
console.log(Object.entries(obj));
키가 숫자가되어야하는 경우 각 쌍의 키를 해당 키로 변환 된 콜백 함수로 대체하는 콜백 함수를 사용하여 결과를 새 배열에 매핑 할 수 있습니다.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
const toNumericPairs = input => {
const entries = Object.entries(input);
return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));
}
console.log(toNumericPairs(obj));
Object.assign
위의 예제에서 화살표 함수와 맵 콜백을 사용하여 Object.assign
할당되는 객체 를 반환하는 사실을 활용하여 하나의 명령으로 유지할 수 있으며 단일 명령 화살표 함수의 반환 값은 명령의 결과입니다.
이것은 다음과 같습니다.
entry => {
entry[0] = +entry[0];
return entry;
}
주석에서 @TravisClarke가 언급했듯이 맵 기능은 다음과 같이 단축 될 수 있습니다.
entry => [ +entry[0], entry[1] ]
그러나 기존 배열을 수정하는 대신 각 키-값 쌍에 대해 새 배열을 작성하므로 키-값 쌍 배열의 양이 두 배가됩니다. 원래 항목 배열에 여전히 액세스 할 수 있지만 해당 항목과 가비지 수집되지 않습니다.
이제 in-place 메소드를 사용하여 키-값 쌍을 보유하는 두 개의 배열 (입력 및 출력 배열)을 계속 사용하더라도 총 배열 수는 하나씩 만 변경됩니다. 입력 및 출력 배열은 실제로 배열로 채워지는 것이 아니라 배열에 대한 참조이며 해당 참조는 메모리에서 무시할만한 공간을 차지합니다.
- 각 키-값 쌍을 제자리에서 수정하면 메모리가 거의 증가하지 않지만 몇자를 더 입력해야합니다.
- 각 키-값 쌍에 대해 새 배열을 만들면 필요한 메모리 양이 두 배가되지만 문자를 조금 더 입력해야합니다.
한 단계 더 나아가 엔트리 배열을 새 배열에 매핑하는 대신 내부에서 수정하여 성장을 완전히 제거 할 수 있습니다.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
const toNumericPairs = input => {
const entries = Object.entries(obj);
entries.forEach(entry => entry[0] = +entry[0]);
return entries;
}
console.log(toNumericPairs(obj));
Object.entries
당신에게 효과가 없다면 또 다른 해결책 .
const obj = {
'1': 29,
'2': 42
};
const arr = Array.from(Object.keys(obj), k=>[`${k}`, obj[k]]);
console.log(arr);
ES6이 표준 인 2018 년에 이러한 답변 중 일부를 요약합니다.
객체로 시작 :
let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
- 맹목적으로 배열에서 값을 얻으려면 키를 신경 쓰지 마십시오.
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.values(obj));
//[9,8,7,6,5,4,3,2,1,0,5]
- 배열에서 쌍을 얻는 간단한 방법 :
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj));
//[["1",9],["2",8],["3",7],["4",6],["5",5],["6",4],["7",3],["8",2],["9",1],["10",0],["12",5]]
- 이전과 동일하지만 각 쌍에 숫자 키가 있습니다.
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).map(([k,v])=>[+k,v]));
//[[1,9],[2,8],[3,7],[4,6],[5,5],[6,4],[7,3],[8,2],[9,1],[10,0],[12,5]]
- 객체 속성을 새 배열의 키로 사용 (드문 배열을 만들 수 있음) :
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).reduce((ini,[k,v])=>(ini[k]=v,ini),[]));
//[undefined,9,8,7,6,5,4,3,2,1,0,undefined,5]
This last method, it could also reorganize the array order depending the value of keys. Sometimes this could be the desired behaviour (sometimes don't). But the advantage now is that the values are indexed on the correct array slot, essential and trivial to do searches on it.
- Map instead of Array
Finally (not part of the original question, but for completeness), if you need to easy search using the key or the value, but you don't want sparse arrays, no duplicates and no reordering without the need to convert to numeric keys (even can access very complex keys), then array (or object) is not what you need. I will recommend Map
instead:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
let r=new Map(Object.entries(obj));
r.get("4"); //6
r.has(8); //true
Use Object.keys
and Array#map
methods.
var obj = {
"1": 5,
"2": 7,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0,
"10": 0,
"11": 0,
"12": 0
};
// get all object property names
var res = Object.keys(obj)
// iterate over them and generate the array
.map(function(k) {
// generate the array element
return [+k, obj[k]];
});
console.log(res);
Use Object.entries
to get each element of Object in key & value
format, then map
through them like this:
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var res = Object.entries(obj).map(([k, v]) => ([Number(k), v]));
console.log(res);
But, if you are certain that the keys will be in progressive order you can use Object.values
and Array#map
to do something like this:
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
// idx is the index, you can use any logic to increment it (starts from 0)
let result = Object.values(obj).map((e, idx) => ([++idx, e]));
console.log(result);
In Ecmascript 6,
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
var res = Object.entries(obj);
console.log(res);
If you are using lodash, it could be as simple as this:
var arr = _.values(obj);
With lodash, in addition to the answer provided above, you can also have the key in the output array.
Without the object keys in the output array
for:
const array = _.values(obj);
If obj is the following:
{ “art”: { id: 1, title: “aaaa” }, “fiction”: { id: 22, title: “7777”} }
Then array will be:
[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]
With the object keys in the output array
If you write instead ('genre' is a string that you choose):
const array= _.map(obj, (val, id) => {
return { ...val, genre: key };
});
You will get:
[
{ id: 1, title: “aaaa” , genre: “art”},
{ id: 22, title: “7777”, genre: “fiction” }
]
ES6 (ES2015)implementation using Set
You can use either Array.from() or Spread syntax
Array.from() Example
const names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
const uniqueNames = Array.from(new Set(names));
console.log(uniqueNames);
Spread syntax Example
const names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames);
Use for in
var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
"8":0, "9":0, "10":0, "11":0, "12":0 };
var objectToArray = function(obj) {
var _arr = [];
for (var key in obj) {
_arr.push([key, obj[key]]);
}
return _arr;
}
console.log(objectToArray(obj));
Recursive convert object to array
function is_object(mixed_var) {
if (mixed_var instanceof Array) {
return false;
} else {
return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
}
}
function objectToArray(obj) {
var array = [], tempObject;
for (var key in obj) {
tempObject = obj[key];
if (is_object(obj[key])) {
tempObject = objectToArray(obj[key]);
}
array[key] = tempObject;
}
return array;
}
We can change Number to String type for Key like below:
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map(function(key) {
return [String(key), obj[key]];
});
console.log(result);
you can use _.castArray(obj).
example: _.castArray({ 'a': 1 }); // => [{ 'a': 1 }]
'Programing' 카테고리의 다른 글
JavaScript에 논리적 xor가없는 이유는 무엇입니까? (0) | 2020.05.18 |
---|---|
공백을 밑줄로 바꾸려면 어떻게해야합니까? (0) | 2020.05.18 |
파이썬에서 왜 바퀴를 만들 수 없습니까? (0) | 2020.05.18 |
React Native Flexbox에서 100 % 너비 (0) | 2020.05.18 |
Ruby On Rails에서 이전 페이지로 리디렉션하는 방법은 무엇입니까? (0) | 2020.05.18 |