【问题标题】:Converting javascript object to ordered comma separated value将javascript对象转换为有序逗号分隔值
【发布时间】:2012-07-12 05:15:48
【问题描述】:

我试图让 json 中的项目有序排列。我能够选择 json 中存在的“术语”值,但是是否可以按照我在预期输出部分中显示的方式进行排列?我添加了一个 jsfiddle 链接来显示我到达的位置:

[
    {
        "Link": "http://testLink.com/1",
        "_index": "test",
        "_source": {
            "Author": "SAM",
            "Map": [
                {
                    "Company": [
                        {
                            "Apple_Inc": [
                                {
                                    "count": 1,
                                    "term": "Apple"
                                }
                            ],
                            "sector": "Technology",
                            "term": "Apple Inc",
                            "ticker": "AAPL",
                            "type": "BCap"
                        }
                    ],
                    "count": 1,
                    "term": "Company"
                },
                {
                    "Country": [
                        {
                            "Canada": [
                                {
                                    "Canada": [
                                        {
                                            "count": 1,
                                            "term": "Toronto"
                                        }
                                    ],
                                    "count": 1,
                                    "term": "Canada"
                                }
                            ],
                            "United_States": [
                                {
                                    "count": 1,
                                    "term": "United States"
                                }
                            ],
                            "currency": "Dollar (USD)",
                            "index": "DOW JONES INDUS. AVG , S&P 500 INDEX , NASDAQ COMPOSITE INDEX",
                            "region": "North Americas",
                            "term": "Canada"
                        }
                    ],
                    "count": 1,
                    "term": "Country"
                },
                {
                    "Personality": [
                        {
                            "count": 1,
                            "term": "Bart Prince"
                        },
                        {
                            "count": 1,
                            "term": "Thomas"
                        },
                        {
                            "count": 1,
                            "term": "Deborah Hornstra"
                        },
                        {
                            "count": 1,
                            "term": "Henderson Sotheby"
                        },
                        {
                            "count": 1,
                            "term": "Max Alliance"
                        }
                    ],
                    "count": 5,
                    "term": "Personality"
                }
            ]
        },
        "id": "YMFT112"
    },
    {
        "Link": "http://testLink.com/2",
        "_id": "YMFT113",
        "_index": "test",
        "_source": {
            "Author": "MAX",
            "Map": [
                {
                    "Company": [
                        {
                            "Microsoft Corp": [
                                {
                                    "count": 1,
                                    "term": "Microsoft"
                                }
                            ],
                            "sector": "Technology",
                            "term": "Microsoft",
                            "ticker": "AAPL",
                            "type": "BCap"
                        }
                    ],
                    "count": 1,
                    "term": "Company"
                },
                {
                    "Country": [
                        {
                            "Brazil": [
                                {
                                    "count": 1,
                                    "term": "Brazil"
                                }
                            ],
                            "currency": "Dollar (USD)",
                            "region": "South Americas",
                            "term": "Brazil"
                        }
                    ],
                    "count": 1,
                    "term": "Country"
                },
                {
                    "SalesRelated": [
                        {
                            "count": 1,
                            "term": "traffic"
                        }
                    ]
                },
                {
                    "Personality": [
                        {
                            "count": 1,
                            "term": "Maximor"
                        },
                        {
                            "count": 1,
                            "term": "R.V.P"
                        },
                        {
                            "count": 1,
                            "term": "Wenger"
                        },
                        {
                            "count": 1,
                            "term": "SAF"
                        }
                    ],
                    "count": 4,
                    "term": "Personality"
                }
            ]
        }
    }
]

http://jsbin.com/exuwet/3/edit


提示输入 如果字段选中 = Country,

预期输出:

YMFT112;    Country;    United States;  United States;      NA;         http://testLink.com/1;

YMFT112;    Country;    Canada;         Canada;             Toronto;    http://testLink.com/1;

YMFT113;    Country;    Brazil;         Brazil;             NA;         http://testLink.com/2;

如果已选择字段 = Company

预期输出:

YMFT112; Company;   Apple Inc;      Apple;      http://testLink.com/1;

YMFT113; Company;   Microsoft Corp; Microsoft;  http://testLink.com/2;

【问题讨论】:

  • 你试过eval('(' + json_object + ')')吗?从那里创建对象不会有问题。
  • 我没试过eval,其实我看过了,我第一次处理josn字符串。
  • 我已经发布了我的答案。请按照说明进行操作,我相信您将能够为您的问题创建解决方案。

标签: javascript arrays json recursion hash


【解决方案1】:

您可以使用原生可用的 JSON 对象或使用 JSON2 作为填充程序。

之后,只需使用 JavaScript 的内置排序功能即可。您提供了一个函数,可以将数组项相互比较

var myArray = JSON.parse(jsonString);
myArray.sort(function(a, b){
    var nameA = a._source.Map.Company.term;
    var nameB = b._source.Map.Company.term;

    if (nameA === nameB) {
        return 0;
    } else if (nameA < nameB) {
        return -1
    }
    return 1;
});

【讨论】:

    【解决方案2】:

    使用eval('(' + json_object + ')'),您将能够创建一个 JavaScript 对象。该对象将是一个数组,您可以使用. 访问属性。 例如,如果您的json_object 被称为数据,例如: 那么

        var temp = eval('(' + data + ')'); // temp now is an array.
    

    如果您想从json 对象访问第一个_indexid

        "_index": "test",
        "id": "YMFT112",
    

    提醒(temp[0]._index),它会显示"test"。对于其他属性,遵循相同的逻辑。 This stackoverflow 问题或JSON 页面将帮助您了解您在其他方面必须做什么才能完成任务。 Yahoo 有一个名为 YUI 的 API,它可能会更有帮助。

    【讨论】:

    【解决方案3】:

    这是使用object-scan的解决方案

    // const objectScan = require('object-scan');
    
    const data = [{"_index":"test","id":"YMFT112","_source":{"Author":"SAM","Map":[{"count":1,"term":"Company","Company":[{"sector":"Technology","ticker":"AAPL","Apple_Inc":[{"count":1,"term":"Apple"}],"term":"Apple Inc","type":"BCap"}]},{"count":1,"term":"Country","Country":[{"region":"North Americas","index":"DOW JONES INDUS. AVG , S&P 500 INDEX , NASDAQ COMPOSITE INDEX","United_States":[{"count":1,"term":"United States"}],"term":"Canada","currency":"Dollar (USD)","Canada":[{"count":1,"term":"Canada","Canada":[{"count":1,"term":"Toronto"}]}]}]},{"count":5,"term":"Personality","Personality":[{"count":1,"term":"Bart Prince"},{"count":1,"term":"Thomas"},{"count":1,"term":"Deborah Hornstra"},{"count":1,"term":"Henderson Sotheby"},{"count":1,"term":"Max Alliance"}]}]},"Link":"http://testLink.com/1"},{"_index":"test","_id":"YMFT113","_source":{"Author":"MAX","Map":[{"count":1,"term":"Company","Company":[{"sector":"Technology","ticker":"AAPL","Microsoft Corp":[{"count":1,"term":"Microsoft"}],"term":"Microsoft","type":"BCap"}]},{"count":1,"term":"Country","Country":[{"region":"South Americas","Brazil":[{"count":1,"term":"Brazil"}],"term":"Brazil","currency":"Dollar (USD)"}]},{"SalesRelated":[{"count":1,"term":"traffic"}]},{"count":4,"term":"Personality","Personality":[{"count":1,"term":"Maximor"},{"count":1,"term":"R.V.P"},{"count":1,"term":"Wenger"},{"count":1,"term":"SAF"}]}]},"Link":"http://testLink.com/2"}];
    
    const find = (term, input) => {
      const r = objectScan([`[*]._source.Map[*].${term}[*].**.term`], {
        reverse: false,
        filterFn: ({ key, parents, context }) => {
          if (Object.values(parents[0]).some((e) => e instanceof Object)) {
            return;
          }
          const root = parents[parents.length - 2];
          context.push([
            root.id || root._id,
            parents[parents.length - 5].term,
            key[key.length - 3].replace(/_/g, ' '),
            ...parents.slice(0, -7).filter((e) => !Array.isArray(e)).map((p) => p.term).reverse(),
            root.Link
          ]);
        }
      })(input, []);
      const maxLength = Math.max(...r.map((e) => e.length));
      r
        .filter((e) => e.length < maxLength)
        .forEach((e) => e.splice(-1, 0, 'NA'.repeat(maxLength - e.length)));
      return r;
    };
    
    console.log(find('Country', data).map((e) => e.join(';    ')).join('\n'));
    /* =>
    YMFT112;    Country;    United States;  United States;      NA;         http://testLink.com/1
    YMFT112;    Country;    Canada;         Canada;             Toronto;    http://testLink.com/1
    YMFT113;    Country;    Brazil;         Brazil;             NA;         http://testLink.com/2
     */
    console.log(find('Company', data).map((e) => e.join(';    ')).join('\n'));
    /* =>
    YMFT112; Company;   Apple Inc;      Apple;      http://testLink.com/1
    YMFT113; Company;   Microsoft Corp; Microsoft;  http://testLink.com/2
     */
    .as-console-wrapper {max-height: 100% !important; top: 0}
    &lt;script src="https://bundle.run/object-scan@13.8.0"&gt;&lt;/script&gt;

    免责声明:我是object-scan的作者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 2015-05-20
      相关资源
      最近更新 更多