var IDs = {};
$.ajax({
url: url,
type: 'GET',
data: {
type: "json",
requestUrl: "requestUrl",
requestWorkflow: "requestWorkflow",
directReply: true
},
dataType: 'json',
success: function( data, textStatus, jQxhr ) {
console.log(data);
IDs= data;
},
error: function(jqXhr, textStatus, errorThrown){
alert( "something went wrong, please try again: " errorThrown );
},
});
console.log(IDs[0]);
Im trying to join objects in an array by their key. I tried some solutions but couldnt fix it. My array is like ;
[0:{Ids: "6",Name: "Michael"}] [1:{Ids: "7",Name: "Gerald"}] [2:{Ids: "8",Name: "Rose"}] [3:{Ids: "9",Name: "Graice"}]
i need like this
[0:{"6":"Michael","7":"Gerald","8":"Rose","9":"Graice"}]
Thanks for help
CodePudding user response:
Based on my comment :
const arr = [
{ Ids: "6", Name: "Michael" },
{ Ids: "7", Name: "Gerald" },
{ Ids: "8", Name: "Rose" },
{ Ids: "9", Name: "Graice" }
]
const singleObject = arr.reduce((acc,curr) => {
return {
...acc,
[curr.Ids] : curr.Name,
};
},{})
const singleObjectJson = JSON.stringify([singleObject])
const singleObjectInArray = [singleObject]
console.log(singleObject)
console.log(singleObjectJson)
console.log(singleObjectInArray)
You should learn more about Array methods and specifically about Array.reduce()
i used here.