javascript - Javascript 或 Ramda 按属性转换 JSON
问题描述
我在我的项目中使用Ramda 库。
是否可以转换以下 JSON 数组
从
[
{
"id": 1,
"name": "test",
},
{
"id": 2,
"name": "test2"
}
];
到
[
{
"id": 1,
"id": 2,
},
{
"name": "test",
"name": "test2"
}
];
请帮忙
解决方案
对象不能具有具有相同键的多个属性,因此
{ "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>
推荐阅读
- swift - 在swift iOS中以编程方式批量设置按钮图像
- javascript - 在附加的 td 上获得 x-editable
- c# - C# WebApi 登录验证
- netlogo - 如何使用两条相交线的概念在 Netlogo 中实现避障(龟头与由补丁组成的墙)
- vue.js - 组件错误地从其他组件输出内容
- blazor - 如何知道 EventCallback 何时被触发?
- openssl - LibreSSL 为 aes-256-gcm 提供身份验证标签
- django - docker容器中的cronjob无法连接到其他容器
- datetime - Hive:在“yyyy-MM-dd'T'HH:mm:ss.SSS'Z'”中转换缺少秒数的字符串日期时间
- java - 如何从数据库中获取数据?