How to Push Array to Json Object in Angular

How to push JSON records into an empty array as individual elements [Angular]

The problem is you are pushing an array into array. You should pushindividual elements and concat arrays.

It should be either:

this.users = json;

Or:

this.users.concat(json);

Or:

this.users.push(...json); // Destructure the array first

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Also, should probably use Angular HttpClient for fetching data.

How to create json object and push array with key/ value pair in angular 4

First, initialise your variable as an Object, keep sliderImages as inner Array.

var obj = {sliderImages: []};

Then push into obj.sliderImages , as below

obj.sliderImages.push({image:URL+element[0]});

Here is the full code,

if (element.optioinimages) {
var obj = {sliderImages: []};
element.optionimages.forEach((element) => {
obj.sliderImages.push({ image: URL + element[0] });
console.log(obj);
}
}

How to push a JSON object to an array in AngularJS

Try with this: Before pushing data you have to check if the survey id exists or not. If it exists you have to update choice with the corresponding survey id, otherwise you can push directly.

$scope.setData = function(survey, choice) {
var item = $filter('filter')(keepAllData, {
surveyId: survey.id
});
if (!item.length) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
} else {
item[0].choiceId = choice.id;
}
console.log(keepAllData);
}

Demo

How to push json values in to an array without getting replaced in angular 6?

Try something like that:

historyT: any = [];
public modelaData = {
name: "",
age: "",
operator: "",
};
public historyModel;

getResponse(){
this.cs.getResponseValue()
.subscribe(responseData => {
this.historyModel = {...this.modelaData}; // <== here just copy object
this.responseData.map((val, i) => {
let a = val.Record.AddDetails;
a.map((vall, i) => {
if (isFromOnCreateAccr) {
this.historyModel.name= a[i].name;
this.historyModel.age= a[i].age;
this.historyModel.operator= a[i].operator;
this.historyT.push(this.historyModel); // Last value is getting replaced here
}
})
})
})
}

My assumption is that you used one object and you were replacing just fields of this object, so as result you had an array of the references to one object which you modified every time. Now you just copy it before filling it with values and inserting it into an array. There are a lot of things that i would implement differently, but this should solve your problem. Hope that helps.



Related Topics



Leave a reply



Submit