ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 객체 배열에서 객체 값을 키 / 값 쌍으로 바꿉니다.
    카테고리 없음 2020. 8. 10. 12:41

    질문

    chartkick 사용에 관심이 있으므로 다음 형식으로 JS 객체를 변환해야합니다.

    var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]

    다음 형식으로 :

    var arrayOne = [{'01/01/2017': 200}, {'02/01/2017': 220},{'03/01/2017':250}]

    어떤 도움이라도 대단히 감사하겠습니다.


    답변1

    Array.prototype.map ( ) :

    const src = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}],
    
          result = src.map(({date,value1}) => ({[date]: value1}))
          
    console.log(result)
    .as-console-wrapper{min-height:100%;}



    답변2

    이 시도:

     var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
     
    let final_array =  array.map(arr => {
        return {[arr.date] : arr.value1};
     })
    
    console.log(final_array)



    답변3

     var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}];
        var mappedArray = array.map(item => {
        return {
            [item.date]: item.value1
        }
    })

    배열을 반복하여 새 구조에 매핑



    답변4

    각 value1, value2, ...에 대해 루프에서 수행하려면

    var array = [{
      date: '01/01/2017',
      value1: 200,
      value2: 300,
      value3: 400
    }, {
      date: '02/01/2017',
      value1: 220,
      value2: 330,
      value3: 430
    }, {
      date: '03/01/2017',
      value1: 250,
      value2: 330,
      value3: 420
    }]
    
    const numberOfValues = 3;
    
    for (let i = 1; i <= numberOfValues; i++) {
      const mappedArray = array.map(x => {
        const result = {};
        result[x.date] = x["value" + i.toString()];
        return result;
      });
      console.log(mappedArray);
    }



    답변5

    해볼 수 있습니다.

    let sampleArray = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
    
    
       let finalArray = sampleArray.map(data => ({[data.date]:data.value1}))
    
    console.log(finalArray)

    출력 :

    [{01/01/2017: 200},{02/01/2017: 220},{03/01/2017: 250}]


     

     

     

     

    출처 : https://stackoverflow.com/questions/63246262/in-array-of-objects-turn-object-values-into-key-value-pair

    댓글

Designed by Tistory.