首页 > 解决方案 > ...Array.from 输出仅显示数组中的最后一个条目。将 JSON 转换为新的对象形式

问题描述

我正在从现有的数组数组创建一个对象,但是当通过 Object.fromEntries、Object.assign 和 ...Array.from 运行数组时,我得到了数组数组中最后一个元素的重复,但另一个元素在数组按预期迭代。

代码将比我能解释的更清楚地表明这一点。我发现很难解释,因为这对我来说非常接近。

这个问题的奇怪之处在于我以前在同一个文件中做过这个,它可以工作。复制代码以将其复制到另一个数组时,它的行为与同一函数的先前版本不同。Console.loging out data at each point 它被操纵表明数据很好,直到 ...Array.from 的结果

更新:添加完整代码以帮助复制问题

这是完整的功能/应用程序

import React, { Component } from "react";
import data from "./data/convertedData/POSTCODES FOR DISTRICT_AVRG HOUSE PRICE - Average price.json";

class JSONCreator extends Component {
    // makeJson = () => {
    //     data.map(i => )

    // }

    // {
    //     "year":,
    //     "location":,
    //     "price":,
    //     "lat-lon":,

    // }

    render() {
        const newData = data.map(i => {
            const j = i.year;
            const values = Object.entries(j);
            Object.fromEntries = arr =>
                Object.assign(
                    {},
                    ...Array.from(arr, ([a, b]) => ({
                        year: a,
                        locationAndPrice: b
                    }))
                );
            const obj = Object.fromEntries(values);
            console.log('obj1', obj)
            return obj;
        });

        const newNewData = newData.map(i => {
            console.log('i.locationAndPrice', i.locationAndPrice)
            const j = i.locationAndPrice;
            const values = Object.entries(j);
            console.log('values', values)
            Object.fromEntries = arr =>
                Object.assign(
                    {},
                    ...Array.from(arr, ([a, b]) => ({
                        location: a,
                        price: b
                    }))
                );
            const obj = Object.fromEntries(values);
            console.log('obj', obj);
            return obj;
        });

        // const newArrayHere = newData.map(i => {
        //  const j = i.locationAndPrice;
        //     const values = Object.entries(j);
        //     console.log('values', {...[values]})

        //  // Object.fromEntries = arr =>
        //  //  Object.assign(
        //  //      {},
        //  //      ...Array.from(arr, (p, l) => ({ p, l }))
        //  //  );
        //     // const obj = Object.fromEntries(values)        

        //  // return obj;
        // });
        // console.log(newArrayHere);

        return <div>hi</div>;
    }
}

export default JSONCreator;

我没有展示的是它是用 CRA(create-react-app)完成的,这是一个组件。它没有在更大规模的应用程序中使用,并且是为了数据转换/实践而构建的。

以下是数据示例:

{
       "year": {
           "Jan-95": {
               "City of London": "91449",
               "Barking & Dagenham": "50460",
               "Barnet": "93285",
               "Bexley": "64958",
               "Brent": "71307",
               "Bromley": "81671",
               "Camden": "120933",
               "Croydon": "69158",
               "Ealing": "79886",
               "Enfield": "72515",
               "Greenwich": "62300",
               "Hackney": "61297",
               "Hammersmith & Fulham": "124903",
               "Haringey": "76288",
               "Harrow": "84770",
               "Havering": "68000",
               "Hillingdon": "73835",
               "Hounslow": "72232",
               "Islington": "92516",
               "Kensington & Chelsea": "182695",
               "Kingston upon Thames": "80876",
               "Lambeth": "67771",
               "Lewisham": "60491",
               "Merton": "82071",
               "Newham": "53539",
               "Redbridge": "72190",
               "Richmond upon Thames": "109326",
               "Southwark": "67885",
               "Sutton": "71537",
               "Tower Hamlets": "59865",
               "Waltham Forest": "61319",
               "Wandsworth": "88559",
               "Westminster": "133025,"
           }
       }
   },

这是我要运行的功能。下面是我运行将上面的 JSON 转换为下面的下一个 JSON 对象


    const newData = data.map(i => {
            const j = i.year;
            const values = Object.entries(j);
            Object.fromEntries = arr =>
                Object.assign(
                    {},
                    ...Array.from(arr, ([a, b]) => ({
                        year: a,
                        locationAndPrice: b
                    }))
                );
            const obj = Object.fromEntries(values);
            return obj;
        });

这是他从上面的函数返回的console.log,和预期的一样

{ 
locationAndPrice: 
     {
         Barking & Dagenham: "50460"
         Barnet: "93285"
         Bexley: "64958"
          Brent: "71307"
         Bromley: "81671"
         Camden: "120933"
         City of London: "91449"
         Croydon: "69158"
         Ealing: "79886"
         Enfield: "72515"
         Greenwich: "62300"
         Hackney: "61297"
         Hammersmith & Fulham: "124903"
         Haringey: "76288"
         Harrow: "84770"
         Havering: "68000"
         Hillingdon: "73835"
         Hounslow: "72232"
         Islington: "92516"
         Kensington & Chelsea: "182695"
         Kingston  upon Thames: "80876"
         Lambeth: "67771"
         Lewisham: "60491"
         Merton: "82071"
         Newham: "53539"
         Redbridge: "72190"
         Richmond upon Thames: "109326"
         Southwark: "67885"
         Sutton: "71537"
         Tower Hamlets: "59865"
         Waltham Forest: "61319"
         Wandsworth: "88559"
         Westminster: "133025,"}


         year:{ "Jan-95"}
       }
}
        const newNewData = newData.map(i => {
            const j = i.locationAndPrice;
            const values = Object.entries(j);
            console.log('values', values)
            Object.fromEntries = arr =>
                Object.assign(
                    {},
                    ...Array.from(arr, ([a, b]) => ({
                        location: a,
                        price: b
                    }))
                );
            const obj = Object.fromEntries(values);
            return obj;
        });

我想把上面的JSON数据转换成这种形式

{
        "location":  "City of London",
        "price": "93285",
},

我目前得到的是

{
              "location": "Westminster",
              "price": "406413",
},

现在这里的问题是,"Westminster"重复作为数据迭代的位置。价格是迭代和独特的。

请提出问题,以便我可以完善此问题并得出结果。

标签: javascriptarraysobjectecmascript-6

解决方案


更新:

我最终自己弄清楚了。与该问题最上部提到的数据相同。

import React, { Component } from "react";
import data from "./data/convertedData/POSTCODES FOR DISTRICT_AVRG HOUSE PRICE - Average price.json";

class JSONCreator extends Component {
    componentDidMount() {
        this.doSomething();
    }
    doSomething = () => {
        const newData = data.map(i => {
            const j = i.year;
            const doStuff = Object.entries(j).map(([key, value]) => [key, value]);
            const entries = doStuff.map(a => ({
                year: a[0],
                locationAndPrice: a[1]
            }));
            return entries;
        });

        const newState = newData.map(i => {
            const j = i[0].year;
            return Object.entries(i[0].locationAndPrice).map(a => ({
                year: j,
                location: a[0],
                price: a[1]
            }));
        });

        console.log("newData", newState);
        this.setState({
            newState: newState
        })
    };

    render() {
        console.log("this.state", this.state);
        return <div>{JSON.stringify(this.state)}</div>;
    }
}

export default JSONCreator;

推荐阅读