如何迭代此json结构以生成另一个结构? [英] How do I iterate over this json structure to produce another structure?

查看:164
本文介绍了如何迭代此json结构以生成另一个结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个json结构。

I have this json structure.

x=[{
    "value": 1.37,
    "date_transacted": "2015-01-01"
}]

来自这个json结构,我想生成以下json结构;

From this json structure, I want to produce the following json structure;

y1=[{
    c: [{
        v: "2015-01-01"
    },
    {
        v: "1.37"
    }]
}]

我已经编写了代码来执行此操作。它看起来像这样;

I have written the code to do this. It looks like this;

var y1 = [{ c:[ {"v":x[0].value}, {"v":x[0].date_transacted} ] }];

我的问题来自 x 有几个json键/值对。看起来像这样的东西;

My problem comes when x has several json key/value pairs. Something that look like this;

x=[{
    "value": 1.37,
    "date_transacted": "2015-01-01"
},
{
    "value": 1.62,
    "date_transacted": "2015-02-01"
},
{
    "value": 1.83,
    "date_transacted": "2015-03-01"
}]

通过对象数组迭代我的代码以产生所需的json结构的有效方法是什么?

What is an effective way to iterate my code through the array of objects to produce the desired json structure which should look like this?

y=[{
    c: [{
        v: "2015-01-01"
    },
    {
        v: "1.37"
    }]
},
{
    c: [{
        v: "2015-01-02"
    },
    {
        v: "1.62"
    }]
},
{
    c: [{
        v: "2015-01-03"
    },
    {
        v: "1.83"
    }]
}]


推荐答案

此处的其他答案(@ user2415266除外)不是动态的,硬编码接受确切的输入,并不是特别可重复使用。如果您有超过2个属性,或者在@ Siguza的情况下,如果您的属性不是'date_transacted'和'value',它们将会失败。

The other answers here (except @user2415266) are not dynamic, hard-coded to accept an exact input, and are not particularly reusable. They will fail if you have more than 2 properties, or in @Siguza's case, also if you have properties not called 'date_transacted' and 'value'.

function restructureJson(obj) {
    var output = {c:[]};
    for (var i in obj) {
        output.c.push({v:obj[i]});
    }
    return output;
}

此函数可在任何大小的任何对象数组中重复使用,包含任何物业数量。

This function is reusable on any array of objects, of any size, containing any number of properties.

// Simple example
var json1 = [{
    "value": 1.37,
    "date_transacted": "2015-01-01"
}];

// More complex
var json2 = [{
    "value": 1.37,
    "date_transacted": "2015-01-01",
    "another_value": "test",
    "more": "12356"
},
{
    "value": 1.62
},
{
    "value": 1.83,
    "date_transacted": "2015-03-01",
    "stuff": "124334654567"
}];

// Map the function to the arrays
a = json1.map(restructureJson);
b = json2.map(restructureJson);

这篇关于如何迭代此json结构以生成另一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆