4

I have an array say

var a = ['N','Normal','S','Severe','C','Confidential']

I need the output format like below,

[{code:'N',description:'Normal'},
 {code:'S',description:'Severe'},
 {code:'C',description:'Confidential'}
]

Is there any way to achieve this?

1
  • please let me know your array pattern is forever like var a = ['N','Normal','S','Severe','C','Confidential'] Commented Dec 15, 2017 at 5:44

1 Answer 1

2

You can use Array.prototype.reduce() as follows:

const array = ['N', 'Normal', 'S', 'Severe', 'C', 'Confidential'];
const object = array.reduce((result, value, i) => {
  i % 2 || result.push({code: value, description: array[i + 1]});
  return result;
}, []);

console.log(object);

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

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.