简体   繁体   English

…Array.from输出仅显示数组的最后一个条目。 将JSON转换为新的对象形式

[英]…Array.from output showing only last entry from array. Converting JSON into new object form

I am creating an object from an existing array of arrays, but when running the arrays through Object.fromEntries, Object.assign and ...Array.from I get a repetition of the last element from the array of arrays but the other element in the array iterates out as intended. 我正在从现有的数组数组中创建对象,但是当通过Object.fromEntries,Object.assign和... Array.from运行数组时,我重复了数组数组中的最后一个元素,但重复了另一个元素数组按预期进行迭代。

The code will show this more clearly than I can explain. 代码将比我无法解释的更加清楚地显示这一点。 I am finding it quite difficult to explain as this is quite near territory for me. 我发现很难解释,因为这对我来说很近。

The odd thing about this problem is I have done this before, in the same file and it works. 关于这个问题的奇怪的事情是我之前在同一文件中完成了此工作,并且可以正常工作。 When copying the code to replicate it on another array it is not behaving as the previous rendition of the same function. 当复制代码以将其复制到另一个数组上时,它的行为不像该函数的先前版本。 Console.logging out the data at each point it is manipulated shows the data is fine, right up until the result of the ...Array.from Console.log在操作的每个点注销数据会显示数据很好,直到... Array.from的结果为止

UPDATE: added full code to help with replication of the issue 更新:添加了完整代码以帮助复制问题

Here is the full function/app 这是完整功能/应用

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;

All that i am not showing is it is done with CRA (create-react-app) and this is a component. 我没有显示的全部是通过CRA(create-react-app)完成的,这是一个组件。 It is not being used in a larger scale app and is being built for the purpose of data conversion/practice. 它并没有在较大规模的应用程序中使用,而是出于数据转换/实践的目的而构建的。

Here is a sample of the data: 这是数据示例:

{
       "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,"
           }
       }
   },

Here is the functions that I am trying to run. 这是我要运行的功能。 Below is what I run to convert the above JSON to the next JSON object below 下面是我将上述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;
        });

This is he console.log returned from the above function, as expected 这是从上述函数返回的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;
        });

I want to convert the above JSON data to this form 我想将上述JSON数据转换为这种形式

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

What I am getting currently is 我现在得到的是

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

Now the issue here is, "Westminster" is getting repeated as the location for iterations of the data. 现在的问题是, "Westminster"被重复用作数据迭代的位置。 The price is iterating and uniquely. 价格是重复的和唯一的。

Please ask questions so I can refine this question and get to a result. 请提出问题,以便我可以对此问题进行细化并得出结果。

UPDATE: 更新:

I ended up figuring it out on my own. 我最终自己弄清楚了。 Same data as mentioned in the upper most part of this question. 与该问题最上部提到的数据相同。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM