对象Convert的JSON数组

时间:2018-12-26 15:22:08

标签: javascript arrays json

这是我的数据数组

let data = [{
    "name": "s1",
    "age": 20,
    "address": "abc"
}, {
    "name": "s2",
    "age": 21,
    "address": "def"
}];

我想将数据数组转换为过滤器数组。

let filters = [
    {
        "field": "name",
        "values": [{
            "label": "s1",
            "value": "s1"
        }, {
            "label": "s2",
            "value": "s2"
        }]
    },
    {
        "field": "age",
        "values": [{
            "label": "21",
            "value": "21"
        }, {
            "label": "20",
            "value": "20"
        }]
    },
    {
        "field": "address",
        "values": [{
            "label": "abc",
            "value": "abc"
        }, {
            "label": "def",
            "value": "def"
        }]
    }
];

3 个答案:

答案 0 :(得分:0)

您可以使用Map来收集相同的field及其值。然后获得带有所需物品的物品。

const
    getValue = v => ({ label: v, value: v });

let data = [{ name: "s1", age: 20, address: "abc" }, { name: "s2", age: 21, address: "def" }],
    filters = Array.from(
        data.reduce((m, o) =>
            Object
                .entries(o)
                .reduce((n, [k, v]) => n.set(k, [...(n.get(k) || []), getValue(v)]), m), new Map),
        ([field, values]) => ({ field, values })
    );
    
console.log(filters);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您需要提取第一个元素的Object.keys或所有可能具有不同键的所有元素,然后map贯穿结果以添加所需的结构:

let data = [{
  "name": "s1",
  "age": 20,
  "address": "abc"
}, {
  "name": "s2",
  "age": 21,
  "address": "def"
}];

let fields = [...new Set(data.map(e => Object.keys(e)).flat())]; // extract the keys

// Or

/*
  let fields = Object.keys(data[0]); // if you're sure that all the array entries have the same fields.
*/

let filters = fields.map(field => ({
  field,
  values: data.map(e => ({
    label: e[field],
    value: e[field]
  }))
}))

console.log(filters)

答案 2 :(得分:0)

首先,定义三个Java DTO,如下所示:

public class Data {
    private String name;
    private String age;
    private String address;
   // getter setter
}

public class Value {
    private String label;
    private String value;
}

public class Response {
    private String field;
    private List<Value> values;
}

第二,主要代码:

public static void main(String[] args) throws Exception {
    File file = new File("inputFileName");
    TypeReference<List<Data>> reference = new TypeReference<List<Data>>() {
    };
    ObjectMapper mapper = new ObjectMapper();
    List<Data> datas = mapper.readValue(file,reference);
    JSONArray object = JSONArray.fromObject(datas);
    Iterator iterator = object.iterator();
    Map<String,List<Value>> var0 = new HashMap<>();
    while (iterator.hasNext()) {
        JSONObject jsonObject = (JSONObject) iterator.next();
        Set<String> keys = jsonObject.keySet();
        for(String key : keys) {
            List<Value> values = var0.get(key);
            if (null == values) {
                values = new ArrayList<>();
                values.add(new Value(jsonObject.getString(key),jsonObject.getString(key)));
                var0.put(key,values);
            } else {
                values.add(new Value(jsonObject.getString(key),jsonObject.getString(key)));
            }
        }
    }
    List<Response> responses = new ArrayList<>(var0.size());
    for(Map.Entry<String,List<Value>>entry:var0.entrySet()) {
        Response response = new Response();
        response.setField(entry.getKey());
        response.setValues(entry.getValue());
        responses.add(response);
    }

    File outPutFile = new File("outputFileName");
    mapper.writeValue(outPutFile,responses);
}