0

I would like to map one array of object into another in a more functional style, I am using typescript.

Basically I am using delete to remove a property on a object, I would like to know if there is a better way to write it.

  const data = props.data.map(d => ({
    order: d.position,
    logs: d.batches.map(b => {
      let log= {
        amount: b.scrap,
        batchNumber: '', // NO GOOD
      }
      if (!b.batch || b.batch.length === 0) {
        delete log.batchNumber // NO GOOD
      }
      return log
    }),
  }))

example input data:

const data = [
    position: 1,
    batches: [
         {batchNumber: '', ammount: 3}
    ]
]

result:

const data = [{
        order: 1,
        logs:[ {ammount:3}]
    }
]
1
  • 1
    Can you give an example of your input/output data? Commented Jan 31, 2018 at 11:43

3 Answers 3

2

You can do another map on the batches to return a new array of objects, and attach that to your returned object instead:

const out = data.map(({ position: order, batches }) => {
  const logs = batches.map(({ batchNumber, ammount }) => {
    if (batchNumber) return { batchNumber, ammount };
    return { ammount };
  });
  return { order, logs }
});

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

I need to add batchNumber if its property exist and its value is different than an empty string, does you code work in this way?
It does now @Radex.
1

One approach would be to make a shallow copy of the target omitting keys you want to delete, for example:

let drop = key => obj => Object.keys(obj).reduce((r, k) =>
    k === key ? r : {...r, [k]: obj[k]}, {});

let test = [
    {foo:11, bar:2, baz: 3},
    {foo:22, bar:2, baz: 3},
    {foo:33, bar:2, baz: 3},
    ];

console.log(test.map(drop('bar')));

Comments

1

To add another option to the mix: it is possible to use Object.assign to optionally assign the property:

const data = [{
  position: 1,
  batches: [{batchNumber: '',ammount: 3}, {batchNumber: 'withNr',ammount: 4}]
}];
 
const res = data.map(d => 
  ({
    order: d.position,
    logs : d.batches.map(({ammount, batchNumber}) => Object.assign({ammount}, batchNumber ? {batchNumber} : null ))
  })
);
 
 console.log(res);

Comments

Your Answer

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.