我具有以下数据结构:
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
我想使用Ramda将其转换为:
const result = [
{
"firstName": "A",
"lastName": "B",
"address": {
"country": "France",
"city": "Paris"
},
},
{
"firstName": "A",
"lastName": "B",
"address": {
"country": "Italy",
"city": "Rome"
},
},
];
答案 0 :(得分:2)
您可以使用converge
函数派生道具address
,然后将其与列表中每个地址的主要对象连接起来:
/**
* R.pick could be replaced with R.omit
* to let you black list properties:
* R.omit(['address']); https://ramdajs.com/docs/#omit
**/
const createByAddress = R.converge(R.map, [
R.pipe(R.pick(['firstName', 'lastName']), R.flip(R.assoc('address'))),
R.prop('address'),
]);
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
console.log(createByAddress(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
答案 1 :(得分:1)
我的问题是为什么“和Ramda一起”?我是Ramda的创始人和忠实粉丝,但这只是一种工具,除非这是Ramda的学习练习,否则似乎没有必要针对此问题使用它。
我会使用现代JS技术做到这一点:
const transform = ({address, ...rest}) =>
address .map (a => ({...rest, address: a}))
const data = {firstName: "A", lastName: "B", address: [{country: "France", city: "Paris"}, {country: "Italy", city: "Rome"}]}
console .log (
transform (data)
)
请注意您的问题所附的评论。 StackOverflow不是代码编写服务。这里的社区希望您能尝试一下并展示出自己陷入困境的地方。
答案 2 :(得分:0)
我不确定这是否对您有帮助,但是如果您想基于adress
生成多个对象,也许会有所帮助
const obj = {
firstName: "a",
lastName: "b",
adresses: [{
country: "France",
city: "Paris"
}, {
country: "Italy",
city: "Rome"
}]
};
adressAmount = obj.adresses.length;
const adressObjects = [];
for (let i = 0; i < adressAmount; i++) {
const {
adresses,
...objWithoutAdresses
} = obj;
objWithoutAdresses.adress = obj.adresses[i];
adressObjects.push(objWithoutAdresses);
}
console.log(adressObjects);
答案 3 :(得分:0)
您可以迭代地址数组并根据需要创建对象
let obj = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
]
}
let newData = obj.address.map(function(item) {
return {
firstName: obj.firstName,
lastName: obj.lastName,
address: {
country: item.country,
city: item.city
}
}
});
console.log(newData)
答案 4 :(得分:0)
我发现这很简单而且简短。
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
let requiredData = data.address.map(element=>{
return {...data,address:element}
})
console.log(requiredData);
答案 5 :(得分:-1)
1)创建一个空字典
2)用于循环数组并将每个数组的索引存储在字典中作为值