I can't seem to find the answer, how to change array in array to object in array ..??
problem this in javaScript. How to convert? How to convert?
I have this array.
[
"or",
[
"or",
{
"status": 1
},
{
"verified": 1
}
],
[
"and",
{
"social_account": 1
},
{
"enable_social": 1
}
]
]
I want this object:
{
"or": [
{
"or": [
{
"status": 1
},
{
"verified": 1
}
]
},
{
"and": [
{
"social_account": 1
},
{
"enable_social": 1
}
]
}
]
}
You can use a recursive function. The base case is when the argument is not an array. In the other case, extract the first array value as key for the object, and map the rest of the array via the recursive function:
const convert = data => Array.isArray(data) && ["or","and"].includes(data[0])
? { [data[0]]: data.slice(1).map(convert) }
: data;
// demo:
let data = ["or",
["or", {"status": 1}, {"verified": 1}],
["and",{"social_account": 1}, {"enable_social": 1}]
];
console.log(convert(data));
Related
For one of my e-commerce application requirement, I have a nested array of the form (Sample):
const data = [
{
"id": 1,
"group": "upper-wear",
"labels": [
{
"type": "shirts",
"quantity": "20",
},
],
popular: true
},
{
"id": 2,
"group": "bottom-wear",
"lables": [
{
"type": "trousers",
"quantity": "31",
},
],
popular: true
},
]
To this array, I need to insert new objects to the array 'labels' if the group value equals 'upper-wear'.
const newDataToInsert = [
{
"type": 'blazers',
"quantity": 19
},
]
This is what I tried so far, considering that for now I only need to insert to single label (i.e. 'upper-wear') (in future, there can be multiple labels category 'upper-wear', 'bottom-wear', to be inserted into):
const updatedArray = data.map((datum) => {
if (datum.group === 'upper-wear') {
return {
...datum,
labels: [...datum.labels, ...newDataToInsert]
};
}
});
console.log(updatedArray);
But there seems to be a silly issue that I am missing as the result returns like this:
[
{
id: 1,
group: 'upper-wear',
labels: [ [Object], [Object] ],
popular: true
},
undefined
]
I know there may be better approaches available, but this is what I can think of as the minimum solution for now.
any help to resolve the current or any better solution will be highly appreciated.
Try with this
updatedArray = data.map((d) => {
if (d.group && d.group === 'upper-wear') {
return { ...d, labels: d.labels.concat(newDataToInsert) }
} else {
return d;
}
})
const data = [
{
"id": 1,
"group": "upper-wear",
"labels": [
{
"type": "shirts",
"quantity": "20",
},
],
popular: true
},
{
"id": 2,
"group": "bottom-wear",
"lables": [
{
"type": "trousers",
"quantity": "31",
},
],
popular: true
},
];
const newDataToInsert = [
{
"type": 'blazers',
"quantity": 19
},
];
const updatedArray = data.map((d) => {
if (d.group && d.group === 'upper-wear') {
return { ...d, labels: d.labels.concat(newDataToInsert) }
} else {
return d;
}
});
console.log(updatedArray)
Explaination
Here while mapping the data, we check for the condition
IF
If it matches then we will first copy the whole object from the variable b return { ...b }
after that we take another variable with the same name lables return { ...d, labels: d.labels.concat(newDataToInsert) },As per the JSON default nature the new variable with the same name will hold the latest value
Here in labels we first take a copy of old data and then merge it with newDataToInsert array labels: d.labels.concat(newDataToInsert), It will merge 2 arrays and store them in JSON with the name labels
Else
In else we just return the current values else { return d; }
You don't actually need to iterate with map over the array. Just find an object in the array and change what you want.
const data=[{id:1,group:"upper-wear",labels:[{type:"shirts",quantity:"20"}],popular:true},{id:2,group:"bottom-wear",lables:[{type:"trousers",quantity:"31"}],popular:true}];
const newDataToInsert=[{type:"blazers",quantity:19}];
data.find(({ group }) => group === 'upper-wear')?.labels.push(...newDataToInsert);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're not returning all objects from your map. you're only returning a result when your criteria is met. This is resulting in your undefined objects...
const data = [
{ "id": 1, "group": "upper-wear", "labels": [ { "type": "shirts", "quantity": "20", }, ], popular: true },
{ "id": 2, "group": "bottom-wear", "lables": [ { "type": "trousers", "quantity": "31", }, ], popular: true },
]
const newDataToInsert = [ { "type": 'blazers',"quantity": 19 }, ]
const updatedArray = data.map(datum => {
if (datum.group === 'upper-wear') datum.labels = [...datum.labels, ...newDataToInsert]
return datum
});
console.log(updatedArray);
You can use Array#find to locate the desired group and then change labels for the group found. There are two options depending on how many items you would like to insert. Use Array#push to add the desired item; use forEach for more than one item:
const searchgroup = "upper-wear";
const target = data.find(({group}) => group === searchgroup);
target.labels.push(...newDataToInsert); //For one item to insert
//newDataToInsert.forEach(label => target.labels.push( label )); //For more than one item
const data = [{"id": 1, "group": "upper-wear", "labels": [{"type": "shirts", "quantity": "20"},],popular: true }, {"id": 2, "group": "bottom-wear", "lables": [{"type": "trousers", "quantity": "31", },],popular: true}];
const newDataToInsert = [{"type": 'blazers', "quantity": 19}];
//group to find
const searchgroup = "upper-wear";
//target element in data
const target = data.find(({group}) => group === searchgroup);
//check if group was found
if( target ) {
//if there's only one product in newDataToInsert us this:
//target.labels.push(...newDataToInsert);
//if you have more than one product to be inserted use this; also works for one
newDataToInsert.forEach(label => target.labels.push( label ));
} else {
console.log( `No such group found: ${searchgroup}!` );
}
console.log( data );
I have an array of objects that determine which ones should be showed first. An example of this array would be:
[
{
"id": "b94ae1a5-c6b2-4e45-87cd-a4036fdb7870",
"prerequisites_ids": [
"2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1"
]
},
{
"id": "ef7d2415-808f-4efc-939e-2692f38a5ee7",
"prerequisites_ids": [
"74e41a2c-e74e-4016-bb2c-f2e84c04fe92"
]
},
{
"id": "74e41a2c-e74e-4016-bb2c-f2e84c04fe92",
"prerequisites_ids": []
},
{
"id": "2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1",
"prerequisites_ids": [
"ef7d2415-808f-4efc-939e-2692f38a5ee7"
]
}
]
How could I sort it to get this?
[
{
"id": "74e41a2c-e74e-4016-bb2c-f2e84c04fe92",
"prerequisites_ids": []
},
{
"id": "ef7d2415-808f-4efc-939e-2692f38a5ee7",
"prerequisites_ids": [
"74e41a2c-e74e-4016-bb2c-f2e84c04fe92"
]
},
{
"id": "2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1",
"prerequisites_ids": [
"ef7d2415-808f-4efc-939e-2692f38a5ee7"
]
},
{
"id": "b94ae1a5-c6b2-4e45-87cd-a4036fdb7870",
"prerequisites_ids": [
"2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1"
]
}
]
I have tried creating a custom function:
export function comparePrerequisites(a, b) {
if (!a.prerequisites_ids) {
return -1
}
if (a.prerequisites_ids.includes(b.id)) {
return 1;
}
}
data.sort(comparePrerequisites)
but does not seem to work. Thanks in advance!
We have here the requirements for a topological sort. This is not a job for the sort method. Instead you can use recursion (a DFS traversal) to drill down to a dependency that is already collected, or to a leaf (no dependencies).
Here is an implementation:
function topologicalSort(tasks) {
const visited = new Set;
const taskMap = new Map(tasks.map(task => [task.id, task]));
function dfs(tasks) {
for (let task of tasks) {
if (!visited.has(task.id)) {
dfs(task.prerequisites_ids.map(id => taskMap.get(id)));
}
visited.add(task);
}
}
dfs(tasks);
return [...visited];
}
// Demo on your example:
let tasks = [{"id": "b94ae1a5-c6b2-4e45-87cd-a4036fdb7870","prerequisites_ids": ["2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1"]},{"id": "ef7d2415-808f-4efc-939e-2692f38a5ee7","prerequisites_ids": ["74e41a2c-e74e-4016-bb2c-f2e84c04fe92"]},{"id": "74e41a2c-e74e-4016-bb2c-f2e84c04fe92","prerequisites_ids": []},{"id": "2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1","prerequisites_ids": ["ef7d2415-808f-4efc-939e-2692f38a5ee7"]}];
console.log(topologicalSort(tasks));
I want to convert object into array of object that fits my needs. I prefer using the most simple solution and smaller amount of code to write. The json is stored inside "monitorings" variable.
monitorings = [
{
"id": 1,
"survey_id": 1,
"region_id": 9101,
"month_id": 1,
"target": 22,
"progress": 22,
"survey": {
"name": "HPG",
"category": "SHP"
},
},
{
"id": 2,
"survey_id": 1,
"region_id": 9102,
"month_id": 1,
"target": 10,
"progress": 10,
"survey": {
"name": "SHPED",
"category": "SHPED"
},
},
}
]
My brain can only think until this code
Object.entries(
monitorings.reduce((monitorings, monitoring) => {
const { name } = monitoring.survey
monitorings[name] = monitorings[name]
? [...monitorings[name], monitoring]
: [monitoring]
return monitorings
}, {})
)
actual output
[
"survey.name", [{grouped object}],
"survey.name", [{grouped object}],
]
expected output
[
"survey.category", [
"survey.name", [{grouped object}],
"survey.name", [{grouped object}],
]
,
"survey.category", [
"survey.name", [{grouped object}],
"survey.name", [{grouped object}],
],
]
Thanks for your help
- Edit -
grouped object's format has the same format as the original object like below
[
{
"id": 2,
"survey_id": 1,
"region_id": 9102,
"month_id": 1,
"target": 10,
"progress": 10,
"survey": {
"name": "SHPED",
"category": "SHPED"
},
},
{same format as above},
{same format as above},
...
],
i found the answer here and modify it.
Object.entries(monitorings.reduce((map, obj) => {
!map[obj.survey["category"]]
? map[obj.survey["category"]] = {}
: [].concat(obj.survey["name"]).forEach(subEl => {
!map[obj.survey["category"]][subEl]
? map[obj.survey["category"]][subEl] = []
: map[obj.survey["category"]][subEl].push(obj);
})
return map;
}, {})
)
explanation
//return convert object into array of object
Object.entries(
//return new form of object
monitorings.reduce((map, obj) => {
//if empty
!map[obj.survey["category"]]
//create new empty object of survey["category"]
? map[obj.survey["category"]] = {}
//else combine all of returned object of survey["name"] into empty array of object
: [].concat(obj.survey["name"])
//iterate over obj.survey["name"]
.forEach(subEl => {
//if that object is empty
!map[obj.survey["category"]][subEl]
//create empty array of survey["category"][subEl]
? map[obj.survey["category"]][subEl] = []
//else push every element of filtered original JSON into array of survey["category"][subEl]
: map[obj.survey["category"]][subEl].push(obj);
})
//return grouped object
return map;
}, {})
)
How do I get the keys "-KTjDx_Ms255rS7GGT7l" for my returned objects so I can access nested data? The data being returned to me from Firebase is one big object containing other objects. It looks like this.
{
"-KTjDx_Ms255rS7GGT7l": {
"questions": [
{
"options": [
{ "isAnswer":false,"text":"dfsf"} , {"isAnswer":false,"text":"fffffff"} , {"isAnswer":false,"text":"fsfsdfs"}
],
"text":"sdfsf"
}
]
},
{
"-KTjDx_Ms255rS7GGT7l": {
"questions": [
{
"options": [
{ "isAnswer":false,"text":"dfsf"} , {"isAnswer":false,"text":"fffffff"} , {"isAnswer":false,"text":"fsfsdfs"}
],
"text":"sdfsf"
}
]
},
{
"-KTjDx_Ms255rS7GGT7l": {
"questions": [
{
"options": [
{ "isAnswer":false,"text":"dfsf"} , {"isAnswer":false,"text":"fffffff"} , {"isAnswer":false,"text":"fsfsdfs"}
],
"text":"sdfsf"
}
]
},
Let's assume your data is called firebaseResponse:
Object.keys( firebaseResponse ).forEach( function( key ) {
var item = firebaseResponse[ key ];
item.questions ...
});
I want to merge item and purchases array of json into one by matching their property value.
Here's the source :
{
"item": [
{
"invoiceId": 1
},
{
"invoiceId": 2
},
{
"invoiceId": 3
}
],
"purchase": [
{
"id": "1",
"date": "12/1/2014"
},
{
"id": "2",
"date": "12/1/2014"
},
{
"id": "3",
"date": "12/1/2014"
}
]
}
I want to produce something like this :
{
"combined": [
{
"invoiceId": 1,
"id": "1",
"date": "12/1/2014"
},
{
"invoiceId": 2,
"id": "2",
"date": "12/1/2014"
},
{
"invoiceId": 3,
"id": "3",
"date": "12/1/2014"
}
]
}
How can I match the item.invoiceId with purchase.id?
Solution
assuming obj is your object
var new_obj = {combined:[]};
obj["purchase"].forEach(function(a) {
obj["item"].forEach(function(b){
if (+b["invoiceId"]===(+a["id"])) {
a["invoiceId"] = b["invoiceId"] || 0;//WILL MAKE INVOICEID 0 IF IT IS NOT DEFINE. CHANGE 0 TO YOUR NEEDS
new_obj.combined.push(a);
}
});
});
How it works
The first .forEach() loops through obj.purchase. Then we loop through obj.item To check if their is a matching invoiceId (if you don't need to make sure their is a matching invoiceId, use the alternate code). Then, we simply add a new value to the new_obj
The result (copied from console) is:
{
"combined":[
{
"id":"1",
"date":"12/1/2014",
"invoiceId":1
},
{
"id":"2",
"date":"12/1/2014",
"invoiceId":2
},
{
"id":"3",
"date":"12/1/2014",
"invoiceId":3
}
]
}
Alternative Code
Use this if you don't need to make sure, invoiceId is there
var new_obj = {combined:[]};
obj["purchase"].forEach(function(a){a["invoiceId"]=a["id"];new_obj.combined.push(a);});
One way of achieving what you want will be
var result = {};
var getMatchingPurchase = function(invoiceId) {
return data.purchase.filter(function(purchase) {
return invoiceId == purchase.id;
})[0];
};
result.combined = data.item.map(function(invoice) {
var purchase = getMatchingPurchase(invoice.invoiceId);
return {
invoiceId: invoice.invoiceId,
id: purchase.id,
date: purchase.date
};
});
console.log(result);
It will print like bellow
{ combined:
[ { invoiceId: 1, id: '1', date: '12/1/2014' },
{ invoiceId: 2, id: '2', date: '12/1/2014' },
{ invoiceId: 3, id: '3', date: '12/1/2014' } ] }
Note:- I'm using map and filter functions which are not supported in IE8. If you want to use in IE8 you have to use for loop.
If you have to support old browsers like IE8 (poor guy...), note that the native forEach might not be supported, in this case you can use lodash for cross-browser compatibility:
function getCombinedResult(source){
var combinedList = [];
_.each(source.item, function(item){
_.each(source.purchase, function(purchase){
if (item['invoiceId'].toString() != purchase['id'].toString()) return;
var combinedItem = _.extend(item, purchase)
combinedList.push(combinedItem);
});
})
return {"combined": combinedList};
}