0

I have an object like this:

{"question": "", "options" : [{"subject": "", "teacher": "", "answer": [] } 
}

I want to copy data from this object into this:

{"question": "", "options" : [{"subject": "", "teacher": "", "new":" " } 
}

I want to add the field "new" instead of "answer"

Nemeth Attila
  • 133
  • 2
  • 13

2 Answers2

1

Deep cloning can be achieved like this: var b = JSON.parse(JSON.stringify(a));

The requested manipulation would be

var a = {"question": "", "options" : [{"subject": "", "teacher": "","answer": [] }}
var b = JSON.parse(JSON.stringify(a))
delete b.options[0].answer
b.options[0].new = 'your content'
lipp
  • 5,586
  • 1
  • 21
  • 32
0

For the sake of another answer... (though I rather liked the first one from @lipp)

Here is a function that deep clones your object and swithches the answer key for the new key.

Problem this will substitue any key answer wherever it may find it. So that if you do this:

clone({"question": "", "answer" : [{"subject": "", "teacher": "", "answer": [] ] } })

Result is

{"question": "", "new" : " " }

var toClone = {"question": "", "options" : [{"subject": "", "teacher": "", "answer": [] ] } };

function clone(original){   
    var copy;

    if (original instanceof Array) {
        copy = [];
        for (var i = 0, limit = original.length; i < limit; ++i) {
            copy[i] = clone(original[i]);
        }
    } else  if (original instanceof Object) { 
        copy = {};
        for (var key in original) {
            if( key === "answer" ){
                copy["new"] = " "; 
            } else
                copy[copiedKey ] = clone(original[key]);
        }
    } else
        copy = original;

    return copy;
}
Chayemor
  • 3,577
  • 4
  • 31
  • 54