How do I convert an object to an array and each scroll it all?
this is my object
let obj = {
each_hour: "20000",
edit_photo: { yes: "20000", no: "0" },
photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
photograph_gender: { male: "0", female: "20000" }
}
Required output:
each_hour
20000
edit_photo
yes
20000
no
0
photo_type
Personal
1000
sport
2100
Industrial
1200
...
As the data stands currently in the object, you can try using JSON.stringify(), replace() and split() like the following way:
let obj = {
each_hour: "20000",
edit_photo: { yes: "20000", no: "0" },
photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
photograph_gender: { male: "0", female: "20000" }
}
var res = JSON.stringify(obj).replace(/["{}]/g,'').split(/[:,]/);
console.log(res);
You can use a recursive function to loop through your object. If an array is passed into your function, you can map each value in the array to the return value of calling your function again on that individual element. If an object is passed through, you can obtain its entries by calling Object.entries() on your object, which will then execute the previously mentioned array mapping. Otherwise, if it's not an array or an object, you can return the value:
function traverseObject(val) {
if(Array.isArray(val)) {
return val.flatMap(elem => traverseObject(elem));
} else if(Object(val) === val) {
return traverseObject(Object.entries(val));
}
return val;
}
const obj = { each_hour: "20000", edit_photo: { yes: "20000", no: "0" }, photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } }, photograph_gender: { male: "0", female: "20000" } }
traverseObject(obj).forEach(e => console.log(e));
You could also use the replacer function of JSON.stringify, as that will be called on every key/value pair in your object, but it's a little bit of a hack:
function traverseObject(obj) {
const res = [];
JSON.stringify(obj, (key, val) => (key !== "" && res.push(key, ...(Object(val) === val ? [] : [val])), val));
return res;
}
// works with arrays -\/
const obj = { foo: [4, 5, 6], each_hour: "20000", edit_photo: { yes: "20000", no: "0" }, photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } }, photograph_gender: { male: "0", female: "20000" } }
traverseObject(obj).forEach(e => console.log(e));
More old school (imperative coding style) approach with recursion if interested :-
Basically maintaining an output array to which we push the key and value obtained from Object.entries. If the value is an object, we recurse and if not we simply push to our output array.
Note - This is specific to your use case and not very generalized.
let obj = {
each_hour: "20000",
edit_photo: { yes: "20000", no: "0" },
photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
photograph_gender: { male: "0", female: "20000" }
}
function objToArray(obj){
const output = [];
function processing(obj){
for (const [key,value] of Object.entries(obj)){
if(typeof value === 'object' ){
output.push(key);
processing(value);
}
else{
output.push(key,value);
}
}
}
processing(obj);
return output;
}
const result = objToArray(obj);
console.log(result);
Related
Given the following Array of Objects:
[
{
"teamFK": 8650,
"code": "yellow_cards",
"typeId": 554,
"value": "5",
"side": "home"
},
{
"teamFK": 8650,
"code": "goals",
"typeId": 554,
"value": "1",
"side": "home"
},
{
"teamFK": 8990,
"code": "yellow_cards",
"typeId": 555,
"value": "2",
"side": "away"
},
{
"teamFK": 8990,
"code": "goals",
"typeId": 555,
"value": "0",
"side": "away"
}
]
I would like to group this data by code and get this result:
{
"stats": [
{
"name": "yellow_cards",
"stats": ["5","2"]
},
{
"name": "goals",
"stats": ["2","0"]
}
]
}
What I've done is the following which works but I want to make sure that the alway the stat with "side":"home" always pushed first into the array "stats": []:
const groupedStats = Object.entries(
query.reduce((acc, { typeId, value, code, side }) => {
if (!acc[code]) {
acc[code] = [];
}
acc[code].push(value);
return acc;
}, {}),
).map(([name, stats]) => ({ name, stats }));
My approach is sort it first by side using Array.sort() and then looping through the objects and adding it to stats
i created a const match to find if there is a match already so i dont have to add the name and value again basically if its not a match i'll add it to the stats array and if its a match then i'll just update the current index
const objs = [
{
teamFK: 8650,
code: "yellow_cards",
typeId: 554,
value: "5",
side: "home",
},
{
teamFK: 8650,
code: "goals",
typeId: 554,
value: "1",
side: "away",
},
{
teamFK: 8990,
code: "yellow_cards",
typeId: 555,
value: "2",
side: "away",
},
{
teamFK: 8990,
code: "goals",
typeId: 555,
value: "0",
side: "home",
},
];
let stats = [];
const transformedObj = objs
.sort((a, b) => {
if (a.side > b.side) {
return -1;
}
if (a.side < b.side) {
return 1;
}
return 0;
})
.forEach((obj) => {
const match = stats.find((stat) => stat.name === obj.code);
const statsIndex = stats.findIndex((stat) => stat.name === obj.code);
if (!match) {
stats = [...stats, { name: obj.code, value: [obj.value] }];
} else {
stats[statsIndex] = {
name: stats[statsIndex].name,
value: [...stats[statsIndex].value, obj.value],
};
}
});
console.log(stats);
You can sort array and use key grouping approach:
const data = [{"teamFK": 8650,"code": "yellow_cards","typeId": 554,"value": "5","side": "home"},{"teamFK": 8650,"code": "goals","typeId": 554,"value": "1","side": "home"},{"teamFK": 8990,"code": "yellow_cards","typeId": 555,"value": "2","side": "away"},{"teamFK": 8990,"code": "goals","typeId": 555,"value": "0","side": "away"}];
const groups = data
.sort(({ side: a }, { side: b }) => b.localeCompare(a))
.reduce((acc, { code, value }) => {
acc[code] ??= { name: code, stats: [] };
acc[code]['stats'].push(value);
return acc;
}, {});
const result = { stats: Object.values(groups) };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
my first time trying to make an api request and get some data is not going to well.
I'm trying to find the "seed":"1" value and get the "franchise_id" value of "0010"
I haven't been successful even getting any of the seeds to console.log
Here is json
{
"version":"1.0",
"playoffBracket":{
"bracket_id":"1",
"playoffRound":[
{
"week":"14",
"playoffGame":[
{
"game_id":"1",
"away":{
"franchise_id":"0002",
"points":"137.2",
"seed":"3"
},
"home":{
"franchise_id":"0008",
"points":"111.7",
"seed":"6"
}
},
{
"game_id":"2",
"away":{
"franchise_id":"0006",
"points":"134.2",
"seed":"4"
},
"home":{
"franchise_id":"0011",
"points":"130.5",
"seed":"5"
}
}
]
},
{
"week":"15",
"playoffGame":[
{
"game_id":"3",
"away":{
"franchise_id":"0006",
"points":"153.3",
"winner_of_game":"2"
},
"home":{
"franchise_id":"0010",
"points":"162.8",
"seed":"1"
}
},
{
"game_id":"4",
"away":{
"franchise_id":"0002",
"points":"95.5",
"winner_of_game":"1"
},
"home":{
"franchise_id":"0012",
"points":"201.7",
"seed":"2"
}
}
]
}
]
},
"encoding":"utf-8"
}
i can log all the data , or some of the inner data , but haven't been able to do much else
$.ajax({
url: "apiurlhere",
success: function (data) {
console.log(data);
console.log(data.playoffBracket);
console.log(data.playoffBracket[0]);
}
});
That's because you are doing it wrong there is no playoffBracket[0] in your data. You need to do below:
data.playoffBracket.playoffRound[0]
To get franchise data you can use below:
data.playoffBracket.playoffRound[0].playoffGame[0].home
Or
data.playoffBracket.playoffRound[0].playoffGame[0].away
To get a single value
data.playoffBracket.playoffRound[0].playoffGame[0].home.franchise_id
Code to find the "seed":"1" value and get the "franchise_id" value of "0010"
// Method for searching
function findInJson(jsonData, findSeed, getFullObject = false) {
let ret = null;
for (let key in jsonData) {
for (let key2 in jsonData[key]) {
let awayHomeData = jsonData[key][key2];
if (Array.isArray(awayHomeData)) {
for (let key3 in awayHomeData) {
if (
awayHomeData[key3].hasOwnProperty("away") ||
awayHomeData[key3].hasOwnProperty("home")
) {
let homeOrAway = awayHomeData[key3];
let homeSeed = homeOrAway.home.seed;
let awaySeed = homeOrAway.away.seed;
if (findSeed == awaySeed) {
ret = homeOrAway.away;
} else if (findSeed == homeSeed) {
ret = homeOrAway.home;
}
}
}
}
}
}
if (ret !== null) {
ret = getFullObject ? ret : ret.franchise_id;
}
return ret;
}
// JSON Data
let data = {
version: "1.0",
playoffBracket: {
bracket_id: "1",
playoffRound: [
{
week: "14",
playoffGame: [
{
game_id: "1",
away: {
franchise_id: "0002",
points: "137.2",
seed: "3",
},
home: {
franchise_id: "0008",
points: "111.7",
seed: "6",
},
},
{
game_id: "2",
away: {
franchise_id: "0006",
points: "134.2",
seed: "4",
},
home: {
franchise_id: "0011",
points: "130.5",
seed: "5",
},
},
],
},
{
week: "15",
playoffGame: [
{
game_id: "3",
away: {
franchise_id: "0006",
points: "153.3",
winner_of_game: "2",
},
home: {
franchise_id: "0010",
points: "162.8",
seed: "1",
},
},
{
game_id: "4",
away: {
franchise_id: "0002",
points: "95.5",
winner_of_game: "1",
},
home: {
franchise_id: "0012",
points: "201.7",
seed: "2",
},
},
],
},
],
},
encoding: "utf-8",
};
// How to utilize the method
console.log(findInJson(data.playoffBracket.playoffRound, 22)); //will display null, because 22 doesn't exist
console.log(findInJson(data.playoffBracket.playoffRound, 2)); //will return 0012
console.log(findInJson(data.playoffBracket.playoffRound, 2, true)); //will return JSON object
The output looks as below:
null
"0012"
{
franchise_id: "0012",
points: "201.7",
seed: "2"
}
The solution can be seen on JSFiddle as well.
For example, given an object with keys and values
{
prefix_1_a: 1a,
prefix_1_b: 1b,
prefix_2_a: 2a,
prefix_2_b: 2b,
}
I want convert into two objects:
prefix_1 with keys and values {a: 1a, b: 1b}
prefix_2 with keys and values {a: 2a, b: 2b}
another example ,given a formData object:
["item_0_orange":"10",
"item_0_apple:"20",
"item_0_grape":"30",
"item_1_orange":"40",
"item_1_apple":"50",
"item_1_grape":"60",
"item_2_orange":"40",
"item_2_apple":"50",
"item_2_grape":"60"]
and I want to convert to json object
fruitprice:
[
{key:0 ,orange:"10" , apple:"20" , grape:"30" },
{key:1 ,orange:"40" , apple:"50" , grape:"60" },
{key:2 ,orange:"40" , apple:"50" , grape:"60" }
]
how to search and add key and value under a position when match same prefix
here is my code:
var fruitObject ={};
for(i=0;i<3;i++)
{
var prefix = "item_" + i;
var res = key.split("_");
var newKey = res[2];
if(key.startsWith(prefix))
{
var newObject = {};
newObject[newKey] =value;
addObject(res[1],newObject, fruitObject); //by given key
return;
};
}
It can be a costly transformation, but not that complex:
Let's start with the input:
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
Then have a look at the desired output:
const fruitprices = [
{
key: 0,
orange: "10",
apple: "20",
grape: "30"
},
{
key: 1,
orange: "40",
apple: "50",
grape: "60",
},
{
key: 2,
orange: "40",
apple: "50",
grape: "60",
}
]
And here's a transformation from data to fruitprices:
// this is an Object, not an Array!
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
// transform function
const fruitprices = Object.entries(data).reduce((a, [key, val]) => {
// destructuring the key; "prefix" is not going to be used
const [prefix, outkey, fruit] = key.split('_')
// trying to find the item in the "a" Array
const item = a.find(({
key: itemkey
}) => itemkey === outkey)
if (item) { // if the key is already in the "a" Array
item[fruit] = val
} else { // if the key is not in the "a" Array yet
a.push({
key: outkey,
[fruit]: val
})
}
return a
}, [])
console.log(fruitprices)
I am trying to create array for ids that are part of rxInfo but are not matching with members ids, but its always push memberIds to mismatchIndexIDs.how to check that condition if value is thereand not matching push it to array.
there could be case i will have 4 members in specialMembers and rxInfos only has 2 passed.
main.ts
for(const member of specialMembers) {
for (const rxInfo of this.rxInfos) {
if (member.indexID === rxInfo.indexID) {
this.indexIDs.push(rxInfo.indexID);
proxyMember = member;
if (!member.dateOfBirth) {
statusDesc = "member dateOfbirth not found";
return Promise.reject(this.errorHandler(request, statusDesc));
}
const requestBody: any = this.buildSingleRequestBody(proxyMember, rxInfo);
const requestObject = this.specialtyQuestionRequest(requestBody);
this.requestArray.push(requestObject);
} else {
this.mismatchIndexIDS.push(rxInfo.indexID);
this.indexIdMismatchCounter++;
}
}
}
data:
"rxInfos": [
{
"drugNdc": "10101",
"rxNumber": "14556459709",
"firstFillIndicator": "N",
"sourceSystem": "TBS",
"indexID": "RPT0ifQ"
},
{
"drugNdc": "101",
"rxNumber": "145945000709",
"firstFillIndicator": "N",
"sourceSystem": "TBS",
"indexID": "GJhQ1MrQnZkTFRR"
}
]
"specialyMembers":[
{
"dob":"12-12-1970"
"firstName": "jimmy",
"lasteName": "shew",
"indexID": "RPT0ifQ"
},
{
"dob":"18-10-1970"
"firstName": "Timmy",
"lasteName": "Doug",
"indexID": "GJhQ1MrQ"
},
{
"dob":"17-06-1981"
"firstName": "John",
"lasteName": "owascar",
"indexID": "GJhQ1MrTGDSRQ"
}
]
Instead of looping over two arrays (O(N^2) operations), transform the first one in a temporary object indexed by the joining key and partition the second array.
function partition(arr, predicate) {
const out = [[],[]];
arr.forEach(e => out[Number(!!predicate(e))].push(e));
return out;
}
const membersByIndex = {}
specialMembers.forEach(m => membersByIndex[m.indexID] = m)
const [mismatch, match] = partition(rxInfo, rx => rx.indexID in membersByIndex)
let jsonObj = {
"compCode": "0001",
"vndrId": "0000000047",
"vndrName": "NKJFKFJFJKJJ",
"vndrName1": "jdkfjfkfjk",
"shortName": "fjkfjkfjkf",
"vndrStatus": "A",
"vndrType": "R",
"docStatus": "O",
"createdOn": "1970-01-01T00:00:00.000+0000",
"modifiedOn": "2017-10-11T10:33:35.000+0000",
"lastUser": "ashok",
"vndrAddr": [{
"addrId": "1",
"addr1": "jhghjbg",
"addr2": "jgbfhhj",
"addr3": "hjvfddfh",
"city": "DJHHVH",
"state": "JH",
"pinCode": "855485",
"effDate": "1970-01-01T00:00:00.000+0000",
"effStatus": "A",
"vndrContact": [{
"contId": "1",
"contName": "gnghh",
"contDesg": "ghhgh",
"contPh": "5625458",
"contEmail": "gfhj#bjhg.com"
}, {
"contId": "1",
"contName": "gnh",
"contDesg": "ghgh",
"contPh": "562558",
"contEmail": "ghj#bjhg.com"
}
]
}, {
"addrId": "2",
"addr1": "jhghjbg",
"addr2": "jgbfhhj",
"addr3": "hjvfddfh",
"city": "DJHHVH",
"state": "JH",
"pinCode": "855485",
"effDate": "1970-01-01T00:00:00.000+0000",
"effStatus": "A",
"vndrContact": [{
"contId": "3",
"contName": "nghh",
"contDesg": "hhgh",
"contPh": "562558",
"contEmail": "gfj#bhg.com"
}, {
"contId": "4",
"contName": "gngh",
"contDesg": "ghhh",
"contPh": "56458",
"contEmail": "gfh#bjh.com"
}]
}],
"vndrRegn": [{
"regnId": 1,
"regnType": "V",
"regnNo": "ABCDEFGHJ",
"regnDate": "2016-10-01T00:00:00.000+0000",
"regnAuth": "jfkjfjfjf",
"regnExpiry": "2022-10-01T00:00:00.000+0000",
"effDate": "2016-10-01T00:00:00.000+0000",
"effStatus": "A"
}, {
"regnId": 2,
"regnType": "S",
"regnNo": "ABCDEFGHJ",
"regnDate": "2016-10-01T00:00:00.000+0000",
"regnAuth": "jfkjfjfjf",
"regnExpiry": "2022-10-01T00:00:00.000+0000",
"effDate": "2016-10-01T00:00:00.000+0000",
"effStatus": "A"
}]
}
My object look like this. How do I rename each key inside an array or object and create a key value array using javascript ?
My result should look like this
compCode:0001
vndrId:00088
vndrName:JXCHXDDJKCJ
vndrName1:JFVHSSSJFDH
shortName:jvgshqxz
vndrStatus:A
vndrType:R
docStatus:O
createdOn:18-10-2017 11:32:28
modifiedOn:23-10-2017 18:51:58
lastUser:ashok
vndrAddr[0].addrId:1
vndrAddr[0].addr1:vfdfvf
vndrAddr[0].addr2:nbnsdvd
vndrAddr[0].addr3:bdfb
vndrAddr[0].city:vbvfb
vndrAddr[0].state:JH
vndrAddr[0].pinCode:3332
vndrAddr[0].effDate:02-10-2012
vndrAddr[0].effStatus:A
vndrAddr[0].vndrContact[0].contId:1
vndrAddr[0].vndrContact[0].contName:jvffvjh
vndrAddr[0].vndrContact[0].contDesg:hvhjjvf
vndrAddr[0].vndrContact[0].contPh:vjhhjv
vndrAddr[0].vndrContact[0].contEmail:fhhf#fj.com
vndrAddr[1].addrId:2
vndrAddr[1].addr1:hjdfhjfhj
vndrAddr[1].addr2:vffvhjh
vndrAddr[1].addr3:hfvfhj
vndrAddr[1].city:hjvhjdf
vndrAddr[1].state:JH
vndrAddr[1].pinCode:255
vndrAddr[1].effDate:02-12-2012
vndrAddr[1].effStatus:A
vndrAddr[1].vndrContact[0].contId:1
vndrAddr[1].vndrContact[0].contName:dfvhjf
vndrAddr[1].vndrContact[0].contDesg:fvjhfvhj
vndrAddr[1].vndrContact[0].contPh:fvhjjhfv
vndrAddr[1].vndrContact[0].contEmail:hdhd#hf.com
You could take an iterative and recursive approach by saving the type for array indices with brackets. Later assign the value the the new property of the path.
function setPath(object) {
function iter(object, path, isArray) {
Object.keys(object).forEach(function (key) {
var temp = path + (isArray ? '[' + key + ']' : (path && '.') + key);
if (object[key] && typeof object[key] === 'object') {
return iter(object[key], temp, Array.isArray(object[key]));
}
result[temp] = object[key];
});
}
var result = {};
iter(object, '');
return result;
}
var object = { a: { b: [{ c: { d: 'foo' } }, 'bar'] } };
console.log(setPath(object));