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"]
}]

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) }))
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)}));
}

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.