I have nested object array in which I would like to create a object in a format
-combine all from cn_from, combine all cn_to with the respective id to new object.
I would like to know how to do using javascript
Tried
var result = getObj(obj);
getObj(obj) {
var getallsrc = obj.map(e => e.cn_from.map(i => [i.cn]));
var getalltar = obj.map(e => e.cn_to.map(i => [i.cn]));
var newobj = [];
newobj.push({ source:getallsrc });
newobj.push({ source:getalltar });
return newobj;
}
Input:
var obj = [
{
"id": "trans",
"cn_from":[{
"cn": "TH",
"ccy": "THB"
},{
"cn": "IN",
"ccy": "INR"
}],
"cn_to":[{
"cn": "AU",
"ccy": "AUD"
},{
"cn": "CA",
"ccy": "CAD"
}]
},
{
"id": "fund",
"cn_from":[{
"cn": "US",
"ccy": "USD"
}],
"cn_to":[{
"cn": "GB",
"ccy": "GBP"
},{
"cn": "PL",
"ccy": "PLD"
}]
}
]
Expected Output:
[{
"id": "trans",
"source": ["TH","IN"],
"target": ["AU", "CA"]
},{
"id": "fund",
"source": ["US"],
"target": ["GB", "PL"]
}]
Jack Bashford
44.3k11 gold badges56 silver badges84 bronze badges
3 Answers 3
It will give you the output you expect.
obj.map(x => ({ id: x.id, source: x.cn_from.map(x => x.cn), target: x.cn_to.map(x => x.cn) }))
answered Aug 22, 2019 at 8:31
Abdulsamet Kurt
1,2502 gold badges12 silver badges16 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You want id, source and target to all be in the same object - use something simple like this. Also make sure you use map on obj, as it is an array.
function getObj(obj) {
return obj.map(({ id, cn_from, cn_to }) => ({ id, source: cn_from.map(({ cn }) => cn), target: cn_to.map(({ cn }) => cn)}));
}
answered Aug 22, 2019 at 8:29
Jack Bashford
44.3k11 gold badges56 silver badges84 bronze badges
Comments
function getObj(obj) {
return obj.map((e) => {
return {
id: e.id,
source: e.cn_from.map((x) => x.cn),
target: e.cn_to.map((x) => x.cn)
};
});
}
var obj = [{
"id": "trans",
"cn_from": [{
"cn": "TH",
"ccy": "THB"
}, {
"cn": "IN",
"ccy": "INR"
}],
"cn_to": [{
"cn": "AU",
"ccy": "AUD"
}, {
"cn": "CA",
"ccy": "CAD"
}]
},
{
"id": "fund",
"cn_from": [{
"cn": "US",
"ccy": "USD"
}],
"cn_to": [{
"cn": "GB",
"ccy": "GBP"
}, {
"cn": "PL",
"ccy": "PLD"
}]
}
];
console.log(getObj(obj))
answered Aug 22, 2019 at 8:31
Azad
5,2825 gold badges32 silver badges59 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js