【问题标题】:Converting javascript array data into an object将javascript数组数据转换为对象
【发布时间】:2022-06-24 19:31:25
【问题描述】:

转换这种类型的数据

const data = [
  { name: 'hcs_utils', starCount: 0 },
  { name: 'K', starCount: 0 },
  { name: 'Heroes of Wesnoth', starCount: 0 },
  { name: 'Leiningen', starCount: 1 },
  { name: 'TearDownWalls', starCount: 1 }]

进入这种对象 {"K":5, "Leiningen":4, ...}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    const data = [
      { name: "hcs_utils", starCount: 0 },
      { name: "K", starCount: 0 },
      { name: "Heroes of Wesnoth", starCount: 0 },
      { name: "Leiningen", starCount: 1 },
      { name: "TearDownWalls", starCount: 1 },
    ];
    
    /* 
        // desired format
        {
            "hcs_utils": 0,
            "K": 0,
            // so on 
        }
    
    */
    
    const formattedDataArray = data.map((each) => {
      const { name, starCount } = each;
      return {
        [name.toString()]: starCount,
      };
    });
    
    console.log("formattedDataArray is", formattedDataArray);
    
    // with reduce
    
    const resultWithReduce = formattedDataArray.reduce((prev, current) => {
      return {
        ...prev,
        ...current,
      };
    }, {});
    
    console.log("resultWithReduce is", resultWithReduce);
    
    // without reduce
    
    let resutlWithoutReduce = {};
    
    formattedDataArray.forEach((eachElement) => {
      const key = Object.keys(eachElement)[0];
      const value = Object.values(eachElement)[0];
      resutlWithoutReduce[key] = value;
    });
    
    console.log("resultWithoutReduce is", resutlWithoutReduce);

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 2021-01-07
      • 1970-01-01
      • 2021-05-07
      • 2021-01-15
      • 2021-06-19
      • 2017-11-13
      • 2014-02-04
      • 2012-03-04
      相关资源
      最近更新 更多