6

i have two object one is for just to hold answer of one question and another is final object. like

  answer = {"value":"asda","indicator":"good"};
  final = {}  ;

i want to append answer object to final object like this

final = {{"value":"asda","indicator":"good"},{"value":"sdad","indicator":"worse"}}

How can i do that ?

6
  • please insert your tried code.. Commented Nov 10, 2016 at 8:25
  • final is not object i think Commented Nov 10, 2016 at 8:25
  • I think it is the same with a question: http://stackoverflow.com/questions/20070790/how-to-append-to-a-json-object-in-angular-js Commented Nov 10, 2016 at 8:26
  • yes @Mahi agreed, final has to be array Commented Nov 10, 2016 at 8:26
  • this is not possible how i am trying here ? @Mahi Commented Nov 10, 2016 at 8:28

4 Answers 4

3
var answer = {"value":"asda","indicator":"good"};

var final = [] //declare it as Array.

final = final.concat(answer);

Updated answer :

With ecma6,its can done using spread operator.

var answer = {"value":"asda","indicator":"good"};
final = {{"value":"sdad","indicator":"worse"}}   
final  = {...final,answer };//final as an object

OR

var answer = {"value":"asda","indicator":"good"}; 
final = {{"value":"sdad","indicator":"worse"}}   
final  = [...final,answer ]; //final as an array.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, the declaration as an array is crucial.
1

You cannot directly append an object. Instead, you need to hold object in an array like following.

answer = {"value":"asda","indicator":"good"};
final = [];
newObject = {"value":"sdad","indicator":"worse"};

now you can push both object to array like -

final.push(answer);
final.push(newObject);

Result of this will be -

final = [{"value":"asda","indicator":"good"},{"value":"sdad","indicator":"worse"}];

1 Comment

your answer is not correct because question is 'how-to-append-object-into-existing-object-angularjs?'. You created an array of 2 objects.
1

In order to append answer object into final , final must be an array

var final =[];
final.push({"value":"asda","indicator":"good"}) 
or
final.push(answer);

Comments

1

If your using ES2015 you could do

const answer = {"value":"asda","indicator":"good"};
const final = [].concat(Object.assign({}, answer))

Or Ghazanfar' is also valid

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.