首页 > 解决方案 > Javascript 或 Ramda 按属性转换 JSON

问题描述

我在我的项目中使用Ramda 库。

是否可以转换以下 JSON 数组

[
   {
     "id": 1,
     "name": "test",
   },
   {
     "id": 2,
     "name": "test2"
   }

];

[
   {
     "id": 1,
     "id": 2,

   },
   {
     "name": "test",
     "name": "test2"
   }

];

请帮忙

标签: javascriptramda.js

解决方案


对象不能具有具有相同键的多个属性,因此 { "id": 1, "id": 2 }{ "name": "test", "name": "test2" }是无效的。我假设您需要一个 id 数组和一个名称数组:

[[1, 2, 3], ['test', 'test2', 'test3']]

如果所有对象都具有相同的键顺序 - 即 no { id: 1, name: 'test'}and { name: 'test2', id: 1 },并且您需要对象中的所有值,则可以将对象映射到它们的值,然后转置:

const { pipe, map, values, transpose } = R;

const fn = pipe(
  map(values),
  transpose,
);

const arr = [{"id":1,"name":"test"},{"id":2,"name":"test2"},{"id":3,"name":"test3"}];

const result = fn(arr);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

如果某些对象有不同的键插入顺序,你想改变结果数组的顺序,或者如果你需要一些键,你可以用 R.props 获取值,然后转置:

const { pipe, map, props, transpose } = R;

const fn = pipe(
  map(props(['name', 'id'])), // example - name would be the 1st sub-array
  transpose,
);

const arr = [{"id":1,"name":"test"},{"id":2,"name":"test2"},{"id":3,"name":"test3"}];

const result = fn(arr);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

如果您想要 Scott Sauyet 建议的结构:

{
  id: [1, 2],
  name: ['test1', 'test2']
}

我会将对象映射并展平为具有 R.chain 和 R.toPairs 的对数组,按每对中的第一项(原始键)对它们进行分组,然后将每个组项映射到每对中的最后一项(原始值)。

const { pipe, chain, toPairs, groupBy, head, map, last } = R

const fn = pipe(
  chain(toPairs),
  groupBy(head),
  map(map(last)), // map(pipe(map(last), uniq)) if you want only unique items
) 

const arr = [{"id":1,"name":"test"},{"id":2,"name":"test2"},{"id":3,"name":"test3"}];

console.log(fn(arr))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js"></script>


推荐阅读