Converting one json object to another with jquery - javascript

i have an input json object , and i want the below output json from a jquery function . How can i achieve it with min lines of code .
Input
{
"dashboardWidgetFacility": [{
"deskUsageInput": {
"breakup": [{
"location_breakup_0": ["{\"id\":1,\"name\":\"campus\"},{\"id\":8,\"name\":\"building \"}"],
"teams_breakup_0": ["3", "6"]
}, {
"location_breakup_1": ["{\"id\":1,\"name\":\"campus\"},{\"id\":8,\"name\":\"building \"},{\"id\":83,\"name\":\"floor \"}"],
"teams_breakup_1": ["3", "2"]
}]
}
}]
}
Output Object
{
"dashboardWidgetFacility": [{
"campus": {
"id": 1
},
"building": {
"id": 8
},
"widgetInput": {
"deskUsageInput": {
"teams": ["3", "6"]
}
}
}, {
"campus": {
"id": 1
},
"building": {
"id": 8
},
"floor": {
"id": 83
},
"widgetInput": {
"deskUsageInput": {
"teams": ["3", "2"]
}
}
}]
}
Here location breakup location_breakup_{index} , has the index.

I had to correct those location_breakup values because you have to parse out the json, but theyre not technically valid json on their own since theyre missing the square brackets on the sides.
const input = {
dashboardWidgetFacility: [
{
deskUsageInput: {
breakup: [
{
location_breakup_0: [
'{"id":1,"name":"campus"},{"id":8,"name":"building "}',
],
teams_breakup_0: ['3', '6'],
},
{
location_breakup_1: [
'{"id":1,"name":"campus"},{"id":8,"name":"building "},{"id":83,"name":"floor "}',
],
teams_breakup_1: ['3', '2'],
},
],
},
},
],
};
const output = Object.values(
input.dashboardWidgetFacility[0].deskUsageInput.breakup
).reduce(
(acc, item) => {
const nestedItem = Object.keys(item).reduce((acc, key) => {
let locationParsed;
let teamsBreakup;
if (key.startsWith('location_breakup')) {
locationParsed = JSON.parse('[' + item[key] + ']');
}
if (key.startsWith('teams_breakup')) {
teamsBreakup = item[key];
}
const obj = (locationParsed || []).reduce(
(acc, item) => {
const { name, id } = item;
return {
...acc,
[name.trim()]: {
id,
},
};
},
{
widgetInput: {
deskUsageInput: {
teams: null,
},
},
}
);
obj.widgetInput.deskUsageInput.teams = teamsBreakup;
return {
...acc,
...obj,
};
}, {});
return {
dashboardWidgetFacility: [...acc.dashboardWidgetFacility, nestedItem],
};
},
{
dashboardWidgetFacility: [],
}
);
console.log(output);

Related

How in JS to merge in one object two json objects where the ID of on object correspond on the same ID of the second object

My question relates to the fact I'm querying 2 different objects from DB and the result is in JSON. I need to merge them into one.
The 2 objects have in common this two key/value IRBId = ... and id = ... and they look as an example
OBJ 1
{
"data":{
"IRBs":{
"nodes":[
{
"id":"8",
"name":"Admin ",
},
{
"id":"9",
"name":"Again",
}
],
}
}
}
OBJ 2
{
"data":{
"informedConsentForms":{
"count":3,
"nodes":[
{
"id":"93",
...
"IRBId":"9",
},
{
"id":"92",
...
"IRBId":"8",
},
{
"id":"91",
...
"IRBId":"8",
}
],
}
},
As you will see above OBJ 2 and OBJ 1 corresponding with the same at IRBid and id.
What I need is to merge the two OBJ where IRBId OBJ 2 === id OBJ 1
The result I would expect after the merge is
OBJ merged
{
[{
"id":"93",
...
"IRBId":"9",
"irb": {
"name":"Again ",
...
}
},
{
"id":"92",
...
"IRBId":"8",
"irb": {
"name":"Admin ",
...
}
},
{
"id":"91",
...
"IRBId":"8",
"irb": {
"name":"Admin ",
...
}
],
},
I don't know how to make it looks like this.
Try using Array.reduce
Logic
Loop through second object data nodes
Find the matching nodes from object 1 data nodes.
Push to accumulator with required details. (I have added only the nodes that was mentioned in in Expected resut, you can add asmuch as you need.)
const obj1 = {
"data": {
"IRBs": {
"nodes": [
{
"id": "8",
"name": "Admin ",
},
{
"id": "9",
"name": "Again",
}
],
}
}
}
const obj2 = {
"data": {
"informedConsentForms": {
"count": 3,
"nodes": [
{
"id": "93",
"IRBId": "9",
},
{
"id": "92",
"IRBId": "8",
},
{
"id": "91",
"IRBId": "8",
}
],
}
},
};
const obj1List = obj1.data.IRBs.nodes;
const output = obj2.data.informedConsentForms.nodes.reduce((acc, curr) => {
const matchingNode = obj1List.find((item) => item.id === curr.IRBId);
if (matchingNode) {
acc.push({
id: curr.id,
IRBId: curr.IRBId,
irb: {
name: matchingNode.name
}
})
}
return acc;
}, []);
console.log(output);
You need to use the map function on the nodes in the first object to construct a new object that contains the second and first object's attributes.
const obj1 = {
"data": {
"IRBs": {
"nodes": [{
"id": "8",
"obj1": "one",
"name": "Admin ",
},
{
"id": "9",
"obj1": "two",
"name": "Again",
}
]
}
}
};
const obj2 = {
"data": {
"informedConsentForms": {
"count": 3,
"nodes": [{
"id": "93",
"obj2": "1",
"IRBId": "9",
},
{
"id": "92",
"obj2": "2",
"IRBId": "8",
},
{
"id": "91",
"obj2": "3",
"IRBId": "8",
}
],
}
}
};
const obj1Data = obj1.data.IRBs.nodes;
const obj2Data = obj2.data.informedConsentForms.nodes;
const res = obj2Data.map(item => {
const obj1Item = obj1Data.find(obj1Item => item.IRBId === obj1Item.id);
return obj1Item ? { ...item, "irb": { ...obj1Item}} : { ...item};
});
console.log(res);
i am using nested loop, try this one
const obj2 = {
"data":{
"informedConsentForms":{
"count":3,
"nodes":[
{
"id":"93",
"IRBId":"9",
},
{
"id":"92",
"IRBId":"8",
},
{
"id":"91",
"IRBId":"8",
}
],
}
},
}
const obj1 = {
"data":{
"IRBs":{
"nodes":[
{
"id":"8",
"name":"Admin ",
},
{
"id":"9",
"name":"Again",
}
],
}
}
}
const result = [];
const obj2Nodes = obj2.data.informedConsentForms.nodes;
for(let i = 0; i < obj2Nodes.length; i++) {
const obj1Nodes = obj1.data.IRBs.nodes
for(let j = 0; j < obj1Nodes.length; j++) {
if(obj2Nodes[i].IRBId === obj1Nodes[j].id) {
const {id, ...reObj1Nodes} = obj1Nodes[j];
result.push({
...obj2Nodes[i],
'irb': {
...reObj1Nodes
}
})
}
}
}
console.log(result)

Skip JSON.map() for the subsequent elements

DEMO
(Please check the browser console for output)
I have a JSON customerItemResponse in a format
{
"totalResults": someNumber,
"results": [
{
"totalItem": 406,
"customerId": "10000"
},
{
"totalItem": 468,
"customerId": "10001"
},
{
"totalItem": 20,
"customerId": "10002"
},
...
Then I have another JSON customerInfo:
{
"totalResults": someNumber,
"results": [
{
"customerId": "10000",
"region": "4",
"area": "42",
},
{
"customerId": "10001",
"region": "4",
"area": "43",
},
{
"customerId": "10002",
"region": "5",
"area": "52",
},
Now I have to create a JSON in a format
[
{
region:'4'
regionDetails:[
{
area:'42'
customerDetails:[
{
customerId:'10000'
totalItem:406
},
{
customerId:'10005'
totalItem:301
},
]
},
{
area:'11'
customerDetails:[
{
customerId:'10010'
totalItem:11
},
{
customerId:'10021'
totalItem:105
},
]
},
]
},
{
region:'5'
regionDetails:[
{
area:'52'
customerDetails:[
{
customerId:'10002'
totalItem:52
},
{
customerId:'10027'
totalItem:310
},
]
},
{
area:'41'
customerDetails:[
{
customerId:'10017'
totalItem:109
},
{
customerId:'10041'
totalItem:450
},
]
},
]
}
]
This is the logic I have written:
customerData=<CustomerDataInterface[]>[]
mapJson() {
this.customerItemResponse.map((res, index) => {
this.customerInfo.find((obj) => {
if (obj.customerId == res.customerId) {
this.customerData.length
? this.customerData.map((data, index1) => {
if (data.region == obj.region) {
data.regionDetails.length
? data.regionDetails.map((regDetails, index2) => {
if (regDetails.area == obj.area) {
regDetails.dealerDetails.push({
customerId: obj.customerId,
totalItem: res.totalItem,
});
return;
}
if (index2 == data.regionDetails.length - 1) {
data.regionDetails.push({ area: obj.area, dealerDetails: [] });
}
})
: data.regionDetails.push({ area: obj.area, dealerDetails: [] });
return;
}
if (index1 == this.customerData.length - 1) {
this.customerData.push({ region: obj.region, regionDetails: [] });
}
})
: this.customerData.push({ region: obj.region, regionDetails: [] });
}
});
});
console.log(this.customerData);
}
Now the output of the console has several region repeated. And suppose if I have 6 unique region but the this.customerData.length is 31.
I think return; is not working as expected. And is not skipping the subsequent element.
here is an efficient way to resolving the issue using js Maps. We can build maps with info about corresponding region and then areas. and after the data is built into maps - convert it back to simple js structures, such as object and arrays
mapJson() {
const customerToTotalMap = new Map(this.customerItemResponse.map(({customerId, totalItem}) => [customerId, totalItem]));
const regionsMap = new Map();
for(let {customerId, region, area} of this.customerInfo) {
let regionAreas;
if(regionsMap.has(region)) {
regionAreas = regionsMap.get(region);
} else {
regionAreas = new Map();
regionsMap.set(region, regionAreas);
}
let areaInfo;
if(regionAreas.has(area)) {
areaInfo = regionAreas.get(area);
} else {
areaInfo = [];
regionAreas.set(area, areaInfo);
}
areaInfo.push({customerId, totalItem: customerToTotalMap.get(customerId)});
}
this.customerData = [...regionsMap.entries()].map(([region, areas]) => ({
region,
regionDetails: [...areas.entries()].map(([area, customerDetails]) => ({
area,
customerDetails
}))
}))
console.log(this.customerData);
}
This is similar to #Andrei's answer. It creates an object literal as mapper. Also, it uses mapping between the region and area when they are created. So, finally you can just get the values of the regionMapper object without going through the mapper objects again
const customerItemResponse=[{customerId:10000,totalItem:77},{customerId:10001,totalItem:37},{customerId:10002,totalItem:295},{customerId:10003,totalItem:458},{customerId:10004,totalItem:248},{customerId:10005,totalItem:35},{customerId:10006,totalItem:280},{customerId:10007,totalItem:147},{customerId:10008,totalItem:439},{customerId:10009,totalItem:401},{customerId:10010,totalItem:489},{customerId:10011,totalItem:414},{customerId:10012,totalItem:287},{customerId:10013,totalItem:391},{customerId:10014,totalItem:125},{customerId:10015,totalItem:207},{customerId:10016,totalItem:197},{customerId:10017,totalItem:151},{customerId:10018,totalItem:225},{customerId:10019,totalItem:333},{customerId:10020,totalItem:361},{customerId:10021,totalItem:225},{customerId:10022,totalItem:242},{customerId:10023,totalItem:150},{customerId:10024,totalItem:52},{customerId:10025,totalItem:475},{customerId:10026,totalItem:494},{customerId:10027,totalItem:30},{customerId:10028,totalItem:189},{customerId:10029,totalItem:112},{customerId:10030,totalItem:482},{customerId:10031,totalItem:283},{customerId:10032,totalItem:159},{customerId:10033,totalItem:440},{customerId:10034,totalItem:461},{customerId:10035,totalItem:76},{customerId:10036,totalItem:84},{customerId:10037,totalItem:392},{customerId:10038,totalItem:296},{customerId:10039,totalItem:293},{customerId:10040,totalItem:135},{customerId:10041,totalItem:348},{customerId:10042,totalItem:338},{customerId:10043,totalItem:444},{customerId:10044,totalItem:15},{customerId:10045,totalItem:32},{customerId:10046,totalItem:67},{customerId:10047,totalItem:277},{customerId:10048,totalItem:65},{customerId:10049,totalItem:95},{customerId:10050,totalItem:290}],
customerInfo=[{customerId:10000,region:"3",area:"32"},{customerId:10001,region:"2",area:"22"},{customerId:10002,region:"2",area:"25"},{customerId:10003,region:"3",area:"31"},{customerId:10004,region:"2",area:"25"},{customerId:10005,region:"1",area:"11"},{customerId:10006,region:"1",area:"14"},{customerId:10007,region:"5",area:"55"},{customerId:10008,region:"5",area:"51"},{customerId:10009,region:"4",area:"45"},{customerId:10010,region:"1",area:"14"},{customerId:10011,region:"1",area:"12"},{customerId:10012,region:"3",area:"33"},{customerId:10013,region:"2",area:"25"},{customerId:10014,region:"4",area:"41"},{customerId:10015,region:"3",area:"32"},{customerId:10016,region:"5",area:"55"},{customerId:10017,region:"2",area:"23"},{customerId:10018,region:"3",area:"33"},{customerId:10019,region:"5",area:"51"},{customerId:10020,region:"4",area:"42"},{customerId:10021,region:"1",area:"12"},{customerId:10022,region:"1",area:"14"},{customerId:10023,region:"1",area:"14"},{customerId:10024,region:"1",area:"13"},{customerId:10025,region:"4",area:"45"},{customerId:10026,region:"3",area:"34"},{customerId:10027,region:"2",area:"24"},{customerId:10028,region:"4",area:"45"},{customerId:10029,region:"2",area:"22"},{customerId:10030,region:"2",area:"22"},{customerId:10031,region:"2",area:"21"},{customerId:10032,region:"3",area:"33"},{customerId:10033,region:"1",area:"11"},{customerId:10034,region:"3",area:"33"},{customerId:10035,region:"3",area:"32"},{customerId:10036,region:"2",area:"22"},{customerId:10037,region:"4",area:"41"},{customerId:10038,region:"3",area:"31"},{customerId:10039,region:"5",area:"51"},{customerId:10040,region:"2",area:"23"},{customerId:10041,region:"4",area:"45"},{customerId:10042,region:"1",area:"14"},{customerId:10043,region:"5",area:"54"},{customerId:10044,region:"3",area:"34"},{customerId:10045,region:"5",area:"51"},{customerId:10046,region:"4",area:"42"},{customerId:10047,region:"5",area:"53"},{customerId:10048,region:"1",area:"11"},{customerId:10049,region:"3",area:"35"},{customerId:10050,region:"5",area:"51"}];
const customerItemMapper = {}
for (const c of customerItemResponse)
customerItemMapper[c.customerId] = c.totalItem
const regionMapper = {},
areaMapper = {};
for (const { customerId, region, area } of customerInfo) {
let regionKey = `Region_${region}`,
areaKey = `Area_${area}`,
totalItem = customerItemMapper[customerId];
if (!(regionKey in regionMapper))
regionMapper[regionKey] = { region, regionDetails: [] }
if (!(areaKey in areaMapper)) {
const o = { area, customerDetails: [] }
areaMapper[areaKey] = o;
regionMapper[regionKey].regionDetails.push(o) // area-region relation
}
areaMapper[areaKey].customerDetails.push({ customerId, totalItem })
}
console.log(Object.values(regionMapper))

How do I extract only those elements from following dictionary which has some data in it?

From this array, i want to select only flipkart and create a new array which contains only flipkart.
json = [
{
"amazon": []
},
{
"flipkart": {
"product_store": "Flipkart",
"product_store_logo": "https://images-api.datayuge.in/image/ZmxpcGthcnRfc3RvcmUucG5n.png",
"product_store_url": "https://price-api.datayuge.com/redirect?id=aHR0cHM6Ly9kbC5mbGlwa2FydC5jb20vZGwvcmVhbG1lLTItZGlhbW9uZC1ibGFjay02NC1nYi9wL2l0bWY4NXNjeHlnaHh3Y2g_cGlkPU1PQkY4NVVZQ0RERlZFRE0mYWZmaWQ9YXJ1bmJhYnVs",
"product_price": "10990",
"product_mrp": "0",
"product_offer": "",
"product_color": "black",
"product_delivery": "3-4",
"product_delivery_cost": "0",
"is_emi": "1",
"is_cod": "1",
"return_time": "10 Days"
}
},
{ "snapdeal": [] },
{ "ebay": [] },
{ "paytm": [] },
{ "croma": [] },
{ "yebhi": [] },
{ "indiatimes": [] },
{ "homeshop18": [] },
{ "naaptol": [] },
{ "infibeam": [] },
{ "tatacliq": [] },
{ "shopclues": [] },
{ "paytmmall": [] },
{ "gadgets360": [] },
{ "mi": [] },
{ "2gud": [] }
];
edit:
above problem is solved, the solution was,
this.store_array.filter(el => {
if(Array.isArray(el[Object.keys(el)[0]])){
return el[Object.keys(el)[0]].length;
}
else if(typeof el[Object.keys(el)[0]]==="object"){
this.brands.push(el[Object.keys(el)[0]])
return el[Object.keys(el)[0]]
}
});
and https://stackoverflow.com/users/8802812/kullya was the one who answered it first but i can't find his answer, since i am new to stackoverflow, all credits goes to user. thank you very much.
You could have a function as below and pass on for which data you might need to find/filter (both works :) ):
var arr= [ { "amazon": [] }, { "flipkart": { "product_store": "Flipkart", "product_store_logo": "https://images-api.datayuge.in/image/ZmxpcGthcnRfc3RvcmUucG5n.png", "product_store_url": "https://price-api.datayuge.com/redirect?id=aHR0cHM6Ly9kbC5mbGlwa2FydC5jb20vZGwvcmVhbG1lLTItZGlhbW9uZC1ibGFjay02NC1nYi9wL2l0bWY4NXNjeHlnaHh3Y2g_cGlkPU1PQkY4NVVZQ0RERlZFRE0mYWZmaWQ9YXJ1bmJhYnVs", "product_price": "10990", "product_mrp": "0", "product_offer": "", "product_color": "black", "product_delivery": "3-4", "product_delivery_cost": "0", "is_emi": "1", "is_cod": "1", "return_time": "10 Days" } }, { "snapdeal": [] }, { "ebay": [] }, { "paytm": [] }, { "croma": [] }, { "yebhi": [] }, { "indiatimes": [] }, { "homeshop18": [] }, { "naaptol": [] }, { "infibeam": [] }, { "tatacliq": [] }, { "shopclues": [] }, { "paytmmall": [] }, { "gadgets360": [] }, { "mi": [] }, { "2gud": [] } ]
function getData (commerceName){
return arr.filter(x=>x[commerceName])
}
// using `find`
// function getData (commerceName){
// return arr.find(x=>x[commerceName])
//}
let res = getData('flipkart')
//let res1 = getData('snapdeal')
console.log(res)
const result = json.find(a => a.hasOwnProperty('flipkart'));
const flipkartData = result ? [result.flipkart] : [];
You can use the .find method of Array and look for the object whose keys contain "flipkart".
(If you actually want just the object instead of wrapping it in an array, you can just omit the [] in the last step.)
const
allData = getAllData(),
flipkart = allData.find(currentItem =>
Object.keys(currentItem).includes("flipkart"));
console.log([flipkart]);
function getAllData(){
return [
{
"amazon": []
},
{
"flipkart": {
"product_store": "Flipkart",
"product_store_logo": "https://images-api.datayuge.in/image/ZmxpcGthcnRfc3RvcmUucG5n.png",
"product_store_url": "https://price-api.datayuge.com/redirect?id=aHR0cHM6Ly9kbC5mbGlwa2FydC5jb20vZGwvcmVhbG1lLTItZGlhbW9uZC1ibGFjay02NC1nYi9wL2l0bWY4NXNjeHlnaHh3Y2g_cGlkPU1PQkY4NVVZQ0RERlZFRE0mYWZmaWQ9YXJ1bmJhYnVs",
"product_price": "10990",
"product_mrp": "0",
"product_offer": "",
"product_color": "black",
"product_delivery": "3-4",
"product_delivery_cost": "0",
"is_emi": "1",
"is_cod": "1",
"return_time": "10 Days"
}
},
{ "snapdeal": [] },
{ "ebay": [] },
{ "paytm": [] },
{ "croma": [] },
{ "yebhi": [] },
{ "indiatimes": [] },
{ "homeshop18": [] },
{ "naaptol": [] },
{ "infibeam": [] },
{ "tatacliq": [] },
{ "shopclues": [] },
{ "paytmmall": [] },
{ "gadgets360": [] },
{ "mi": [] },
{ "2gud": [] }
];
}

manipulate two array of objects make new array and update the attribute of object1 and add in the new array

Hi I am trying to compare two array of objects and want to achieve the custom array of object by manipulating it.
I would like to achieve something like this by checking each time anything from object1 is removed or not? if it is removed then it should change attribute to 'Y'.
object 1 = [
{
"label":"a",
"removed":"N",
"value":1
},
{
"label":"b",
"removed":"N",
"value":2
}
]
object 2 =[
{
"label":"a",
"removed":"N",
"value":1
},
{
"label":"c",
"removed":"N",
"value":3
}
]
result should be =
[{
label:"a",
removed:"N",
value:1
},{
label:"b",
removed:"Y",
value:2
},{
label:"c",
removed:"N",
value:3
}]
I have tried to loop both array and tried to achieve the same but it is somehow not working.
I tried following code.
let data = []
object1.forEach((item1) => {
object2.forEach((item2) => {
if (item1.value === item2.value) {
data.push(Object.assign(item1));
} else {
item2.removeFlag = 'Y';
data.push(Object.assign(item1, item2));
}
}
}
...Updated Question.....
obj1 = [
{
"val":"type1",
"removed":"N",
"data":[
{
"label":"type1-a",
"removed":"N",
"dataid":16
},
{
"label":"type1-b",
"removed":"N",
"dataid":26
}
]
},
{
"val":"type2",
"removed":"N",
"data":[
{
"label":"type2-a",
"removed":"N",
"dataid":12
},
{
"label":"type2-b",
"removed":"N",
"dataid":34
}
]
},
{
"val":"type3",
"removed":"N",
"id":124,
"label":"type3-label1"
},
{
"val":"type4",
"removed":"N",
"id":126,
"label":"type4-label1"
},
{
"val":"type4",
"removed":"N",
"id":128,
"label":"type4-label2"
}
]
obj2 = [
{
"val":"type1",
"removed":"N",
"data":[
{
"label":"type1-a",
"removed":"N",
"dataid":16
},
{
"label":"type1-c",
"removed":null,
"dataid":null
},
{
"label":"type1-d",
"removed":null,
"dataid":null
}
]
},
{
"val":"type3",
"removed":"N",
"id":124,
"label":"type3-label1"
},
{
"val":"type4",
"removed":"N",
"id":126,
"label":"type4-label1"
},
{
"val":"type4",
"removed":null,
"id":null,
"label":"type4-label3"
}
]
result = [
{
"val":"type1",
"removed":"N",
"data":[
{
"label":"type1-a",
"removed":"N",
"dataid":16
},
{
"label":"type1-b",
"removed":"Y",
"dataid":26
},
{
"label":"type1-c",
"removed":null,
"dataid":null
},
{
"label":"type1-d",
"removed":null,
"dataid":null
}
]
},
{
"val":"type2",
"removed":"Y",
"data":[
{
"label":"type2-a",
"removed":"N",
"dataid":12
},
{
"label":"type2-b",
"removed":"N",
"dataid":34
}
]
},
{
"val":"type3",
"removed":"N",
"id":124,
"label":"type3-label1"
},
{
"val":"type4",
"removed":"N",
"id":126,
"label":"type4-label1"
},
{
"val":"type4",
"removed":"Y",
"id":128,
"label":"type4-label2"
},
{
"val":"type4",
"removed":null,
"id":null,
"label":"type4-label3"
}
]
const object1 = [{
"label": "a",
"removed": "N",
"value": 1
},
{
"label": "b",
"removed": "N",
"value": 2
}
]
const object2 = [{
"label": "a",
"removed": "N",
"value": 1
},
{
"label": "c",
"removed": "N",
"value": 3
}
]
const result = [...object2.map(record => {
const record2 = object1.find(pr => pr.label === record.label) || {};
return {
...record,
...record2
}
}), ...object1.filter(pr => !object2.some(npr => npr.label === pr.label)).map(pr => ({ ...pr,
removed: "Y"
}))]
console.log(result);
--Edit
With nested data you have to repeat the same code inside reduce function.
Example
const result = [...object2.map(record => {
const record2 = object1.find(pr => pr.val === record.val) || {};
const data = [...(record.data || []).map(pr => ({ ...pr,
...(record2.data.find(npr => npr.label === pr.label) || {})
})),
...(record2.data || []).filter(pr => !record.data.some(npr => npr.label === pr.label)).map(pr => ({ ...pr,
removed: 'Y'
}))
]
return {
...record,
...record2,
data
}
}), ...object1.filter(pr => !object2.some(npr => npr.val === pr.val)).map(pr => ({ ...pr,
removed: "Y"
}))]

Filtering nested nested array

Hi have this array:
[ {
"Navn": "Long Island Iced Tea",
"Nummer": "2",
"Glas i ml": "250",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive lime",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Cointreau": 20
}
],
"Del2": [
{
"Gin": 20
}
],
"Del3": [
{
"Rom_Lys": 20
}
],
"Del4": [
{
"Tequila": 20
}
],
"Del5": [
{
"Vodka": 20
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Cola": 40
}
],
"Del2": [
{
"Sprite": 20
}
]
},
{
"Type": "Mixer",
"Del1": [
{
"Lime_Sirup": 20
}
]
}
]
}]
Its for a Cocktailmachine.
And i want to filter it by "Del1" searching for (example) "Rom_Lys" & "Cola" & "Vodka", and then output a new array with these specifications.
I tried searching the forums, but can't seem to find something useful. Played around with filter and includes, but cant come up with anything useful.
Thx!
If you want to get items which are contains Cola, then you can use filter and some methods:
const filterWord = 'Cola';
const result = sampleData.filter(s =>
s.Ingredienser.some(s =>
s.Del1.some( e=> e[filterWord])));
console.log(result);
An example:
let sampleData = [
{
"Navn": "Rom & Cola/ Cuba Libre",
"Nummer": "0",
"Glas i ml": "200",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive citron",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Rom_Lys": 40
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Cola": 100
}
]
},
{
"Type": "Mixer",
"Del1": [
{}
]
}
]
},
{
"Navn": "Isbjørn",
"Nummer": "1",
"Glas i ml": "200",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive citron",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Vodka": 30
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Sprite": 60
}
]
},
{
"Type": "Mixer",
"Del1": [
{
"Blå_Sirup": 30
}
]
}
]
}];
const filterWord = 'Cola';
const result = sampleData.filter(s => s.Ingredienser.some(s => s.Del1.some( e=> e[filterWord])));
console.log(result);
UPDATE:
If you want to check multiple key, then you can use hasOwnProperty method which checks whether the object contains desired key:
const filters = ['Cointreau', 'Gin', 'Rom_Lys'];
const result = sampleData.filter(s =>
s.Ingredienser.some(ingred => {
return Object.keys(ingred).some(k=> {
if (Array.isArray(ingred[k])) {
return ingred[k].some(s=> filters.some(f=> {
return s.hasOwnProperty(f);
}))
}
});
}
));
And the example:
let sampleData = [ {
"Navn": "Long Island Iced Tea",
"Nummer": "2",
"Glas i ml": "250",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive lime",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Cointreau": 20
}
],
"Del2": [
{
"Gin": 20
}
],
"Del3": [
{
"Rom_Lys": 20
}
],
"Del4": [
{
"Tequila": 20
}
],
"Del5": [
{
"Vodka": 20
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Cola": 40
}
],
"Del2": [
{
"Sprite": 20
}
]
},
{
"Type": "Mixer",
"Del1": [
{
"Lime_Sirup": 20
}
]
}
]
}];
const filters = ['Cointreau', 'Gin', 'Rom_Lys'];
const result = sampleData.filter(s =>
s.Ingredienser.some(ingred => {
return Object.keys(ingred).some(k=> {
if (Array.isArray(ingred[k])) {
return ingred[k].some(s=> filters.some(f=> {
return s.hasOwnProperty(f);
}))
}
});
}
));
console.log(result);
Try using following code to filter the array.
var filtered = arr.filter(function(unique) {
for (var index = 0; index < unique.Ingredienser.length; index++) {
if (unique.Ingredienser[index].Del1[0].hasOwnProperty(selectedchoice)) {
return true;
}
}
return false;
});

Categories

Resources