prosource

JSON 개체를 JavaScript 배열로 변환하는 방법

probook 2023. 2. 27. 22:27
반응형

JSON 개체를 JavaScript 배열로 변환하는 방법

JSON 오브젝트 문자열을 JavaScript 배열로 변환해야 합니다.

이것은 나의 JSON 오브젝트입니다.

{"2013-01-21":1,"2013-01-22":7}

그리고 나는 다음을 원한다.

var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');

data.addRows([
    ['2013-01-21', 1],
    ['2013-01-22', 7]
]);

어떻게 하면 좋을까요?

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

JSON 문자열이 올바르게 설정되어 있는 경우는, 다음의 조작을 실시할 수 있습니다.

var as = JSON.parse(jstring);

AJAX를 통해 어레이를 전송할 때는 항상 이 작업을 수행합니다.

예를 들어 다음과 같습니다.

var j = {0: "1", 1: "2", 2: "3", 3: "4"};

값은 다음과 같이 얻을 수 있습니다(실제로 모든 브라우저 버전에서 지원됩니다).

Object.keys(j).map(function(_) { return j[_]; })

또는 단순하게:

Object.values(j)

출력:

["1", "2", "3", "4"]
function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

자세한 것은, http://book.mixu.net/node/ch5.html 를 참조해 주세요.

이렇게 하면 문제가 해결됩니다.

const json_data = {"2013-01-21":1,"2013-01-22":7};

const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);

console.log(arr);

또는 Object.entries() 메서드를 사용합니다.

console.log(Object.entries(json_data));

어느 경우든 출력은 다음과 같습니다.

/* output: 
[['2013-01-21', 1], ['2013-01-22', 7]]
*/

위의 솔루션은 중첩된 개체에는 작동하지 않습니다.중첩된 객체의 경우 다음과 같은 작업을 수행할 수 있습니다.

const isObject = (obj) => {
  return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
}

const objToArray = (obj) => {
  return Object.keys(obj).map((key) => {
    return [
      key, isObject(obj[key]) ? 
        objToArray(obj[key]) :
        obj[key]
    ];
  });    
}

const json_data = {
  "2013-01-21":1, 
  "2013-01-22":7,
  "ab":{"x":{"xa": 3, "xb": 4}, "y": 2},
};

console.log(JSON.stringify(objToArray(json_data)));

이 경우의 출력은 다음과 같습니다.

/* output: 
[["2013-01-21",1],["2013-01-22",7],["ab",[["x",[["xa",3],["xb",4]]],["y",2]]]]
*/

다음과 같이 객체 항목을 배열에 삽입할 수 있습니다.

 
 let obj2 = {"2013-01-21":1,"2013-01-22":7}
 
 console.log(Object.keys(obj2).map(key => [key, obj2[key]]))

let obj = {
  '1st': {
    name: 'stackoverflow'
  },
  '2nd': {
    name: 'stackexchange'
  }
};

// you can use Object.values(obj)
console.log(Object.values(obj))
 
// or you can use this instead. 
 let wholeArray = Object.keys(obj).map(key => obj[key]);

 
 console.log(wholeArray);
 console.log(Object.values(obj));

오브젝트 배열을 작성하는 것이 목적이라면 Object.keys()를 사용하여 실행하려는 작업을 수행하는 솔루션을 다음에 제시하겠습니다.

const jsonResponse = '{"2013-01-21":1,"2013-01-22":7}'
// Only use json parse if the data is a JSON string.
const obj = typeof jsonResponse === 'string' ? JSON.parse(jsonResponse) : jsonResponse;
const data = [];

Object.keys(obj).forEach((key) => data.push({[key]: obj[key]}))
// Example 2 - storing it directly in a variable using map
const arrayOfObjs = Object.keys(obj).map((key) => ({[key]: obj[key]}))

또는 Object.entries()를 사용합니다.

// Example 1
Object.entries(obj).forEach((array) => data.push({[array[0]]: array[1]}))
// Example 2
Object.entries(obj).forEach(([key, value]) => data.push({[key]: value}))
// Example 3 - Store it directly in a new variable using map
const arrayOfObjs = Object.entries(obj).map(([key, value]) => ({[key]: value}))

변환할 json 개체를 갖는 것을 고려합니다.

const my_object = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

사용할 수 있는 솔루션은 다음과 같습니다.

1. Object.keys()Object.values()

이러한 함수는 모든 개체를 배열로 변환합니다.하나는 모든 키를 포함한 배열을 반환하고 다른 하나는 모든 값을 반환합니다.

console.log(Object.keys(my_object))
// Output : ["key1", "key2", "key3"]

console.log(Object.values(my_object))
// Output : ["value1", "value2", "value3"]

첫 번째 질문을 이해할 수 있을지 모르겠지만 해결책은 아마

data.addRows(Object.values(my_object));

2. Object.entries()

이 기능은 위의 두 가지를 혼합한 것입니다.

console.log(Object.entries(my_object))
// Output : [["key1", "value1"],  ["key2", "value2"],  ["key3", "value3"]]

첫 번째 질문에는 소용없지만, 이 기능은 매우 유용하기 때문에 언급하지 않을 수 없습니다.특히 value_가 중첩된 개체인 경우.예를 들어 다음과 같은 오브젝트입니다.

const my_object = {
    "key1": {"a": 1, "b": 2},
    "key2": {"y": 25, "z": 26},
    "key3": {"much": "stuff"}
}

그리고 우리는 이런 어레이로 끝맺기를 바란다.

my_array = [
    {"key": "key1", "a": 1, "b": 2},
    {"key": "key2", "y": 25, "z": 26},
    {"key": "key3", "much": "stuff"}
]

사용할 필요가 있다Object.entries()우리의 모든 열쇠를 그들의 가치로 얻을 수 있습니다.자세한 코드는 다음과 같습니다.

my_array = Object.entries(my_object).map(function(entry){
   key = entry[0];
   value = entry[1];

   nested_object = value;
   nested_object.key = key;

   return nested_object;
});

console.log(my_array);
// Expected output : [
//    {"key": "key1", "a": 1, "b": 2},
//    {"key": "key2", "y": 25, "z": 26},
//    {"key": "key3", "much": "stuff"}
//]

확산 연산자를 사용하여 코드를 단순화할 수 있습니다.

my_array = Object.entries(my_object).map(entry => {"key": entry[0], ...entry[1]});

console.log(my_array);
// Expected output : [
//    {"key": "key1", "a": 1, "b": 2},
//    {"key": "key2", "y": 25, "z": 26},
//    {"key": "key3", "much": "stuff"}
//]

@Mister Aqua's SOLUTION에 약간의 수정 사항 있음

const my_array = [];
    Object.entries(set_of_objects).map(function (entry) {
      const key = entry[0];
      const value = entry[1];

      const nested_object = {};

      nested_object[key] = value;
      my_array.push(nested_object);
    });

냉각제 :)

긴 JSON 문자열을 숨겨진 div에 넣고 이 코드로 JSON으로 변환하려고 했을 때 이 오류가 발생했습니다.

var data = document.getElementById('data');
var json = JSON.parse(data);

아직 발견되지 않았나요?네, 덧붙이는 것을 잊었습니다..innerHTML첫 번째 줄에 있습니다. 그래서 데이터는 이미 객체입니다.문자열이 아닙니다.오브젝트를 JSON.parse로 해석하려면 어떻게 해야 합니까?

JSON.parse는 문자열을 해석하기 위해 작성되었습니다.오브젝트가 아닙니다.

이렇게 간단해!

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);

언급URL : https://stackoverflow.com/questions/14528385/how-to-convert-json-object-to-javascript-array

반응형