1

I would like to transform the below JSon. The input JSon array can be of any size. I know its a basic question but I can't find the duplicate.

 var input = [{
    "value": 1
 }, {
    "value": 2
 }]

 var output = [{
    "key": {
        "value": 1
    }
 }, {
    "key": {
        "value": 2
    }
 }]

Appreciate all the help.

1
  • what are you transforming this json array into? - Commented Mar 6, 2017 at 14:51

3 Answers 3

3

Create a new array and use Array#forEach to push an object with key = key and a currently iterated object from input as the value.

var input = [{value:1},{value:2}],
    result = [];
    input.forEach(v => result.push({ 'key': v }));
    
    console.log(result);

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

Comments

2

Try using this, this should solve your problem

output = input.map(value => ({ "key": value }) );
console.log(output);

I used ES6 for simplicity, but this does exactly the same.

3 Comments

you could wrap the object in parens input.map(value => ({ "key": value }));
Right. Thanks :) Updated the answer now.
I agree. It is simpler and more complex at the same time, but that is a different discussion altogether.
-1

I think this will be the most oldschool and hands-on way of doing this.

var input = [{
    "value": 1
 }, {
    "value": 2
 }],
 output = [],
 newItem,
 i = 0, ii = input.length;
 
 
 for(i; i<ii; i++){
  newItem = {};
  newItem.key = {"value":input[i].value};
  output.push(newItem);
 }
 
 console.log(output)

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.