1

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
asked Aug 22, 2019 at 8:23

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.