JS map two object/array - javascript

I have 2 objects with format:
obj1 = [
{
"code": "in_today",
"text": "Today"
},
{
"code": "in_week",
"text": "This week"
},
{
"code": "in_month",
"text": "This month"
},
{
"code": "normal",
"text": "Other"
}
]
obj2 stores "code" value which defined in obj1:
obj2 = ["in_today", "in_week", "normal"]
How can I use obj2's values to change obj1 into something likes:
[
{
"code": "in_today",
"text": "Today",
"selected": true
},
{
"code": "in_week",
"text": "This week",
"selected": true
},
{
"code": "in_month",
"text": "This month",
"selected": false
},
{
"code": "normal",
"text": "Other"
"selected": true
}
]
What's the best solution for this case?
Thanks!

You can use Array.map to transform your objects based on whether their code is in the obj2 array:
var obj1 = [
{
"code": "in_today",
"text": "Today"
},
{
"code": "in_week",
"text": "This week"
},
{
"code": "in_month",
"text": "This month"
},
{
"code": "normal",
"text": "Other"
}
]
var obj2 = ["in_today", "in_week", "normal"]
var newObject = obj1.map(function(obj) {
if (obj2.indexOf(obj.code) > -1) {
obj.selected = true;
} else {
obj.selected = false;
}
return obj;
})
console.log(newObject)
Or a bit simpler if ES6 is available:
const newObject = obj1.map((obj) => {
obj.selected = obj2.includes(obj.code);
return obj;
})

Simple&quick solution using Array#forEach.
var obj1 = [{"code":"in_today","text":"Today"},{"code":"in_week","text":"This week"},{"code":"in_month","text":"This month"},{"code":"normal","text":"Other"}],
obj2 = ["in_today", "in_week", "normal"];
obj1.forEach(v => v.selected = obj2.indexOf(v.code) > -1);
console.log(obj1);

You'll want to do something like this:
for (var i = 0; i < obj1.length; ++i) {
if (obj2.indexOf(obj1[i].code) == -1) {
obj1[i].selected = false;
} else {
obj1[i].selected = true;
}
}
Essentially, you just loop over obj1, then check if the value of obj1.code is present in obj2, then set selected accordingly.

obj1 = [
{
"code": "in_today",
"text": "Today"
},
{
"code": "in_week",
"text": "This week"
},
{
"code": "in_month",
"text": "This month"
},
{
"code": "normal",
"text": "Other"
}
]
obj2 = ["in_today", "in_week", "normal"];
obj1.forEach( function(elem){
if( obj2.indexOf(elem.code) > -1)
elem.selected = true;
else
elem.selected = false;
});
console.log( JSON.stringify(obj1) );

Related

How do I destructure this deep nested json objects and map it in JS

I have a nested array like below. There are about 100 de objects in the array. The de objects also have deg[0] array but most likely I will only have the first index. Now the trick is that the de are subset of deg. Which means each deg can have say 10 de. How can I retrieve the deg and there associated de and map it into a new array like:
newArray = [
deg1: [
{de1},
{de2}
],
deg2: [
{de1},
{de2}
]
]
Here is my nested array. I posted four but the list is over a 100.
{
"name": "Report",
"id": "2YYUEZ6I1r9",
"dse1": [
{
"de1": {
"name": "Number",
"id": "HjMOngg3kuy",
"de1-av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg1": [
{
"name": "TB",
"id": "2XJB1JO9qX8"
}
]
}
},
{
"de2": {
"name": "Number of",
"id": "a3dtGETTawy",
"de2-av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg1": [
{
"name": "Secondary",
"id": "w99RWzXHgtw"
}
]
}
},
{
"de1": {
"name": "Number of",
"id": "a3dtGETTawy",
"de1av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg2": [
{
"name": "Secondary",
"id": "w99RWzXHgtw"
}
]
}
},
{
"de2": {
"name": "Number of",
"id": "a3dtGETTawy",
"de2av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg2": [
{
"name": "Tertiary",
"id": "w99RWzXHgtw"
}
]
}
}
]
}
Group array of objects by property (this time a property to be matched by a reg exp) using Array.reduce.
Update: Ignoring missing keys.
var input={name:"Report",id:"2YYUEZ6I1r9",dse1:[{de1:{name:"Number",id:"HjMOngg3kuy","de1-av":[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg1:[{name:"TB",id:"2XJB1JO9qX8"}]}},{de2:{name:"Number of",id:"a3dtGETTawy","de2-av":[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg1:[{name:"Secondary",id:"w99RWzXHgtw"}]}},{de1:{name:"Number of",id:"a3dtGETTawy",de1av:[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg2:[{name:"Secondary",id:"w99RWzXHgtw"}]}},{de2:{name:"Number of",id:"a3dtGETTawy",de2av:[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg2:[{name:"Tertiary",id:"w99RWzXHgtw"}]}}]}
var reg = new RegExp("^de[0-9]+$");
var reg2 = new RegExp("^deg[0-9]+$");
let obj = input['dse1'].reduce(function(agg, item) {
// do your group by logic below this line
var key = Object.keys(item).find(function(key) {
return key.match(reg) ? key : null;
})
if (key) {
var key2 = Object.keys(item[key]).find(function(key) {
return key.match(reg2) ? key : null;
})
agg[key] = agg[key] || [];
if (key2) {
var to_push = {}
to_push[key2] = item[key][key2]
agg[key].push(to_push)
}
}
// do your group by logic above this line
return agg
}, {});
console.log(obj)
.as-console-wrapper {
max-height: 100% !important;
}

Empty array when filter inside deep an object

I made this function to filter in deep an array of object, but at the end the result is empty. If i check with console.log inside the if statement , it show me filtered object, but resultPost return me empty value. I also tryed to push inside an empty array the filtered value, but not work.
const post = [{
"name": "new post",
"description": "simple desc",
"taxonomies": {
"categories": {
"0": {
"term_id": 15
},
"1": {
"term_id": 20
},
}
}
},
{
"name": "new post 2",
"description": "simple desc 2",
"taxonomies": {
"categories": {
"0": {
"term_id": 11
},
"1": {
"term_id": 12
},
}
}
}
];
const filterID = [15, 1];
const resultPost = post.filter(post => {
if ((post.taxonomies.categories.filter(postct => postct.term_id === filterID)).length > 0) return post
});
console.log(resultPost);
You could filter the posts by matching the taxonomies.categories[id].term_id as follows:
const post = [{
"name": "new post",
"description": "simple desc",
"taxonomies": {
"categories" : {
"0" : {
"term_id" : 15
},
"1" : {
"term_id" : 20
},
}
}
},
{
"name": "new post 2",
"description": "simple desc 2",
"taxonomies": {
"categories" : {
"0" : {
"term_id" : 11
},
"1" : {
"term_id" : 12
},
}
}
}];
const filterID = [15,1];
const resultPost = post.filter(item => {
const { categories } = item.taxonomies;
return Object.keys(categories).reduce((cats, id) => {
filterID.includes(categories[id].term_id) && cats.push(id);
return cats;
}, []).length
});
console.log( resultPost)
Like said in comments, you can't use filter on an Object.
Try this instead
const resultPost = post.filter(post => {
for (let cat in post.taxonomies.categories) { // one way to loop over objects
// filterId is an array so you can't just use ===
if (filterID.includes(post.taxonomies.categories[cat].term_id)) return true;
}
return false;
});
Inside filter, you can take Object.values of that object and then use some based on your condition to filter out records. Something like this:
const post = [{ "name": "new post", "description": "simple desc", "taxonomies": { "categories": { "0": { "term_id": 15 }, "1": { "term_id": 20 }, } } }, { "name": "new post 2", "description": "simple desc 2", "taxonomies": { "categories": { "0": { "term_id": 11 }, "1": { "term_id": 12 }, } } }];
const filterID = [15,1];
const result = post.filter(p=>Object.values(p.taxonomies.categories).some(n=>filterID.includes(n.term_id)));
console.log(result);

Filtration of multilevel JSON array

I am trying to duplicate value only one time as well as unique from my JSON array.
I have tried the following code.
return_data = {};
return_data.planner = [{
"date": "2019-08-30T12:10:08.000Z",
"event": [{
"name": "Event 1",
"color": "#ccccc"
}]
},
{
"date": "2019-09-30T10:10:08.000Z",
"event": [{
"name": "Event 5",
"color": "#ccccc"
},
{
"name": "Event 4",
"color": "#ccccc"
},
{
"name": "Event 3",
"color": "#ccccc"
}
]
},
{
"date": "2019-09-30T10:10:08.000Z",
"event": [{
"name": "Event 5",
"color": "#ccccc"
},
{
"name": "Event 4",
"color": "#ccccc"
},
{
"name": "Event 3",
"color": "#ccccc"
}
]
},
{
"date": "2019-09-30T10:10:08.000Z",
"event": [{
"name": "Event 5",
"color": "#ccccc"
},
{
"name": "Event 4",
"color": "#ccccc"
},
{
"name": "Event 3",
"color": "#ccccc"
}
]
}
];
res.header('Content-Type', 'application/json');
res.send(JSON.stringify(return_data));
Using above json array:
var u_array = [];
var tem = JSON.parse(JSON.stringify(return_data.response.planner));
for (var i = 0; i < tem.length; i++) {
console.log(tem[i].date);
var status = true;
for (var j = 0; j < u_array.length; j++) {
if (u_array[j].date == tem[i].date) {
status = false;
break;
}
}
if (status) {
u_array.push(tem[i]);
}
};
return_data.response.planner = u_array;
I expect the duplicate value only one time with unique values.
There are many different ways to do what you need. You can follow this thread for some pointers.
Here's one way to get distinct-
/**
* inputArray = Input array
* keySelector = A function to select which key should be used to determine if element is distinct
* keepFirstMatch =
* true - If there is a matching element, and you want to keep the first original item
* false - If there is a matching element and you want to override the original item so that it gets overwritten by latest value in the array
*/
function getDistinct(inputArray, keySelector, keepFirstMatch = false) {
const result = inputArray.reduce((acc, curr) => {
if (keepFirstMatch) {
if (typeof (acc[keySelector(curr)]) === 'undefined') {
acc[keySelector(curr)] = curr;
}
} else {
acc[keySelector(curr)] = curr;
}
return acc;
}, {});
return Object.keys(result).map(k => result[k]);
}
let distinct = getDistinct(planner, (c) => c.date);

custom jstree JSON data parse into tree

i have a simple JSON data which is this :
[
"env/child1/env/key1",
"env/child1/key1",
"env/child1/key2",
"env/child1/",
"env/child2/key1",
"env/child2/key2",
"env/child2/",
"env/"
]
how can i make jsTree understands this tree and draw the tree ?
env
child1
key1
key2
do i need to write a custom parsing function or is there a ready way for that.
tree = {
'core' : {
'data' : [
]
}
}
data = [
"env/child1/env/key1",
"env/child1/key1",
"env/child1/key2",
"env/child1/",
"env/child2/key1",
"env/child2/key2",
"env/child2/",
"env/"
];
minlen = -1;
picked = "";
for(i =0; i<data.length; i++) {
if(data[i].length < minlen || minlen == -1) {
minlen = data[i].length;
picked = data[i];
}
}
tree.core.data.push({ "id" : picked, "parent" : "#", "text" : picked })
xdata = data
xdata.splice(xdata.indexOf(picked), 1)
for(i =0; i<xdata.length; i++) {
name = xdata[i]
parent = ""
if(name.substr(name.length-1,1) == '/') {
xname = name.substr(0,name.length-1);
parent = xname.substr(0,xname.lastIndexOf("/")+1)
} else {
parent = name.substr(0,name.lastIndexOf("/")+1)
}
tree.core.data.push({ "id" : name, "parent" : parent, "text" : name })
}
console.log(tree);
I followed the alternative JSON format.
Result:
{
"core": {
"data": [
{
"id": "env/",
"parent": "#",
"text": "env/"
},
{
"id": "env/child1/env/key1",
"parent": "env/child1/env/",
"text": "env/child1/env/key1"
},
{
"id": "env/child1/key1",
"parent": "env/child1/",
"text": "env/child1/key1"
},
{
"id": "env/child1/key2",
"parent": "env/child1/",
"text": "env/child1/key2"
},
{
"id": "env/child1/",
"parent": "env/",
"text": "env/child1/"
},
{
"id": "env/child2/key1",
"parent": "env/child2/",
"text": "env/child2/key1"
},
{
"id": "env/child2/key2",
"parent": "env/child2/",
"text": "env/child2/key2"
},
{
"id": "env/child2/",
"parent": "env/",
"text": "env/child2/"
}
]
}
}
The above data missing parent "env/child1/env/" for child "env/child1/env/key1"
1. correct as follow:
data = [
"env/child1/env/"
"env/child1/env/key1",
"env/child1/key1",
"env/child1/key2",
"env/child1/",
"env/child2/key1",
"env/child2/key2",
"env/child2/",
"env/"
];
The complete code for parent getting the children's values as below:
https://github.com/peterhchen/700-jstree/blob/master/08_PathJSON/0802_PathChild2ParentValueHier.htm

value got overwritten assigning json value within loop

How can I produce something like this?
{
"drink": {
"2": {
"name": "coke",
"type": "drink"
},
"3": {
"name": "coke",
"type": "drink"
}
},
"food": {
"id": "1",
"name": "1 Hour Snooker",
"type": "food"
}
}
I have problem producing multiple object under 'drink' object. It got overwritten with my below code:
http://jsfiddle.net/jLgh4at5/
var json = {
"results": {
"slots": [{
"id": "3",
"name": "pepsi",
"type": "drink"
}, {
"id": "1",
"name": "1 Hour Snooker",
"type": "food"
}, {
"id": "2",
"name": "coke",
"type": "drink"
}]
}
}
var data = {
"slots": {
}
}
json.results.slots.forEach(function (b) {
if (b["type"] == "food") {
data.slots["food"] = b;
} else {
data.slots["drink"] = b;
}
});
console.log(data);
Use array index to resolve the issue.
json.results.slots.forEach(function (b,i) {
if (b["type"] == "food") {
if(data.slots["food"])
data.slots["food"][i] = {"name":b.name,"type":"food"};
else
data.slots["food"] = {};
} else {
if(data.slots["drink"])
data.slots["drink"][i] = {"name":b.name,"type":"drink"};
else
data.slots["drink"] = {};
}
});
Or you can optimize the code as shown below.
var data = {
"slots": {
"food": {},
"drink": {}
}
};
json.results.slots.forEach(function (b,i) {
if (b["type"] == "food") {
data.slots["food"][i] = {"name":b.name,"type":"food"};
} else {
data.slots["drink"][i] = {"name":b.name,"type":"drink"};;
}
});
Here is the updated JSFiddle

Categories

Resources