I want to convert my object status field that is would be modified specifically.
I have found the answer but no fill my goal that's why I updated my question
I have objects like this below:
Items = [
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": 1
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 2
},
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 3
}
]
I need to convert my object like below or I need to print like belows:
[
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": {
"1": "ACTIVE"
}
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": {
"2": "INACTIVE"
}
},
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": {
"3": "DELETED"
}
}
]
For example:
const possibleStatus = {
1: 'ACTIVE',
2: 'INACTIVE'
}
Items.map(item => ({...item, status: {[item.status]: possibleStatus[item.status]}}))
Update: addded lookup via possibleStatus
If nullish coalescing operator ?? is available, I would add a fallback for undefined status:
Items.map(item => ({...item, status: {[item.status]: possibleStatus[item.status] ?? `UNDEFINED STATUS ${item.status}`}}))
but only if this is display logic. In case of business logic, I'd rather check for valid values and throw an exception, e.g. encapsulated in a function mapping the status string to the object.
let statusTable = {
1: "ACTIVE",
2: "INACTIVE",
3: "DELETED"
}
let Items = [
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": 1
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 2
},
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 3
}
]
let result = Items.map(el => {
el.status = { [el.status]: statusTable[el.status] }
return el;
})
console.log(result);
I hope this solution be useful for you.
Items = [
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": 1
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 2
}
]
Items = Items.map(item => {
item.status = item.status == 1 ? { "1": "ACTIVE" } : { "2": "INACTIVE" }
return item;
} )
console.log(Items);
If this is json, first you might want to parse it with JSON.parse, like following:
let parse = JSON.parse(yourJsonObj)
Next you get your array, which you need to modify. You can use map method and return a new array with the data you need:
let newData = parse.map(item => {
item.status = { [item.status]: "INACTIVE" };
return item;
});
Then you can go back and stringify it back if needed with JSON.stringify(newData).
The rules by which you set INACTIVE or ACTIVE I don't know, but this is the gist of it.
As others have indicated, map() is the way to go.
I've stepped things out a little here in such a way that the system wouldn't have unintended consequences if a third property was introduced. The switch statement explicitly only changes things if the status is 1 or 2 and leaves things alone otherwise.
The other examples given are probably fine for your use case though.
var items = [ { "id": 9, "alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1", "name": "sfasf", "status": 1 }, { "id": 5, "alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98", "name": "Test", "status": 2 },
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 3
} ];
const process = () => {
// render original
const orig = document.querySelector('.original');
orig.innerHTML = '';
items.forEach(i => orig.innerHTML += `<li>${i.status}</li>`);
var result = items.map(i => {
switch(i.status) {
case(1):
i.status = {"1": "ACTIVE"}
break;
case(2):
i.status = {"2": "INACTIVE"}
break;
case(3):
i.status = {"3": "DELETED"}
break;
default:
// if status is not 1, 2 or 3, do nothing to the object
break;
}
// return the object
return i
})
// render processed
const res = document.querySelector('.results');
res.innerHTML = '';
items.forEach(i => res.innerHTML +=
`<li>${JSON.stringify(i.status)}</li>`);
}
process()
<div class="cols">
<div>
<p>Original</p>
<ul class="original">
</ul>
</div>
<div>
<p>Result</p>
<ul class="results"></ul>
</div>
Related
Remove data from my nested array of objects by matching values. In my case I want to strip out the objects that are NOT active. So every object that contains active 0 needs to be removed.
[
{
"id" : 1,
"title" : 'list of...',
"goals": [
{
"id": 1569,
"active": 0
},
{
"id": 1570,
"active": 1
},
{
"id": 1571,
"active": 0
}
],
},
{
"id" : 2,
"title" : 'more goals',
"goals": [
{
"id": 1069,
"active": 0
},
{
"id": 1070,
"active": 1
},
],
},
]
The following will return the array in an unchanged status
public stripGoalsByInactiveGoals(clusters) {
return clusters.filter(cluster =>
cluster.goals.filter(goal => goal.active === 1)
);
}
array.filter wait a boolean to know if it has to filter data or not
in your case you have an array of array, you want to filter "sub" array by active goal
if you want to keep only active goals change your first filter by map to return a modify value of your array filtered by a condition
function stripGoalsByInactiveGoals(clusters) {
return clusters.map(cluster => {
return {
goals: cluster.goals.filter(goal => goal.active)
};
});
}
var data = [{
"goals": [{
"id": 1569,
"active": 0
},
{
"id": 1570,
"active": 1
},
{
"id": 1571,
"active": 0
}
],
},
{
"goals": [{
"id": 1069,
"active": 0
},
{
"id": 1070,
"active": 1
},
],
},
];
function stripGoalsByInactiveGoals(clusters) {
return clusters.map(cluster => {
return {
goals: cluster.goals.filter(goal => goal.active)
};
});
}
console.log(stripGoalsByInactiveGoals(data));
You can create another array (for the case when you need the input unchanged as well) and loop the input, appending each member objects' filtered goals array. You could also avoid appending the item if goals is empty after the filter, but this example doesn't do this, because it was not specified as a requirement.
let input = [
{
"goals": [
{
"id": 1569,
"active": 0
},
{
"id": 1570,
"active": 1
},
{
"id": 1571,
"active": 0
}
],
},
{
"goals": [
{
"id": 1069,
"active": 0
},
{
"id": 1070,
"active": 1
},
],
},
]
let output = [];
for (let item of input) {
output.push({goals: item.goals.filter(element => (element.active))})
}
console.log(output);
You can follow this for a dynamic approach:
stripGoalsByInactiveGoals(clusters) {
var res = [];
this.data.forEach((item) => {
let itemObj = {};
Object.keys(item).forEach((key) => {
itemObj[key] = item[key].filter(x => x.active != 0);
res.push(itemObj);
});
});
return res;
}
Stackbiltz Demo
I need inner join with two array in javascript like this:
array1 =
[
{
"id": 1,
"name": "Tufan"
},
{
"id": 2,
"name": "Batuhan"
},
{
"id": 3,
"name": "Hasan"
}
]
array2 =
[
{
"name": "yyy",
"externalid": "1",
"value": "Asd"
},
{
"name": "aaaa"
"externalid": "2",
"value": "ttt"
}
]
expectedArray =
[
{
"id": 1,
"name": "Tufan",
"externalid": "1",
"value": "Asd"
},
{
"id": 2,
"name": "Batuhan",
"externalid": "2",
"value": "ttt"
}
]
rules:
on: array2.externalid = array1.id
select: array1.id, array1.name, array2.externalid, array2.value
My approach:
array1.filter(e => array2.some(f => f.externalid == e.id));
// I need help for continue
How can I make this?
Doesn't matter information: I use ES5 and pure javascript
You can do it like this:
const res = array2.map((item) => {
const related = array1.find((el) => el.id == item.externalid);
return { ...item, ...related };
});
Using a map to loop over the array2 and a find to get the array1 relative.
I have the following input object
{
"id": 1,
"isLeaf": false,
"name": "New rule",
"pid": 0,
"dragDisabled": true,
"children": [
{
"id": "new1",
"value": "data1",
"then": false,
"type": "set",
"forEach": false,
"pid": 1
},
{
"id": "new2",
"value": "data2",
"then": true,
"type": "if",
"forEach": false,
"pid": 1,
"children": [
{
"id": "new3",
"type": "Then",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new5",
"value": "data3",
"then": false,
"type": "fuzzy_search",
"forEach": false,
"pid": "new3"
}
]
},
{
"id": "new4",
"type": "Else",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new6",
"value": "data4",
"then": false,
"type": "return",
"forEach": false,
"pid": "new4"
}
]
}
]
}
]
}
I need to convert it into the following json
[
{
"id": "new1",
"condition": "data1"
},
{
"id": "new2",
"condition": "data2",
"then": [{
"id": "new5",
"condition": "data3"
}],
"else": [{
"id": "new6",
"condition": "data4"
}]
}
]
I have to recursively iterate through all existing inner child array of the input json array to formulate the output.
Following is the partially implemented code for the functionality.
ruleJSONFormatter = (request, parentItem, innerJSON) => {
try {
var outerObject = request;
if (outerObject.children && outerObject.children.length) {
var innerArray = outerObject.children;
// second iteration with inner children
innerArray.forEach((innerItem, index) => {
let parentObj = {};
let recursiveObj = {}; let thenArray = [];
recursiveObj['condition'] = innerItem.value && innerItem.value != undefined ? innerItem.value.formatedData : {};
recursiveObj['type'] = innerItem.type;
recursiveObj['id'] = innerItem.id;
recursiveObj['pid'] = innerItem.pid;
if (innerItem.children && innerItem.children != undefined && innerItem.children.length) {
switch (innerItem.type) {
case 'if':
recursiveObj['then'] = [];
recursiveObj['else'] = [];
}
if (Object.keys(parentObj).length == 0) {
parentObj = recursiveObj;
} else {
}
ruleJSONFormatter(innerItem, parentItem, parentObj)
} else {
if (Object.keys(parentObj).length == 0)
responseArray.push(innerJSON);
}
});
}
else {
console.log("No Values Inside the Formated Data ")
}
console.log("output-----------");
console.log(JSON.stringify(responseArray));
return responseArray
} catch (error) {
console.log('((((((((((((((((((((((((((', error)
}
}
final output array has a condition key which binds the value key from the input json and 'then' key which contains the multiple successive inner children array which is the success condition for type 'if' object. similar is the case for 'else' key in output
I find it hard to recursively call the same function to generate the desired output. the problem arises when there are deep nesting in the children array.Any help is appreciated.Thanks.
I have a api response that return this :
{
"code": 0,
"message": "hierarchy list",
"payload": [
{
"id": 2,
"name": "nameParent",
"code": "WUcw",
"childsOfPayload": [
{
"id": 5,
"name": "NameChild1",
"code": "ozyW",
"status": "Active",
"childsofChildOfPayload": [
{
"id": 8,
"name": "NameChild2",
"code": "aitq",
"order": 30,
},
]}]}]}
I am trying to get the differents objects in each childs, ChildOfPayload and childOfChildOfpayload.
First I've returned the different name value of payload:
getAllPayloadName() {
this.userService.getName().subscribe(
data => {
this.values= data;
}
);
}
But what must I do to get the name of each child assosiated to the different parent value!
I mean in this case.
NameChild1
NameChild2
I've tried this:
manipulateDataa() {
this.values.subscribe(x => {
x.payload.foreach((y:any) => {
y.childs.foreach((z:any) => {
console.log( z.name)
})
})
})
}
then call it in getAllPayloadName, but still don't work. What could be wrong?
You could do something like this to get your desired output. Here you can read more about forEach loop which I have used.
data = {
"code": 0,
"message": "hierarchy list",
"payload": [
{
"id": 2,
"name": "nameParent",
"code": "WUcw",
"childsOfPayload": [
{
"id": 5,
"name": "NameChild1",
"code": "ozyW",
"status": "Active",
"childsofChildOfPayload": [
{
"id": 8,
"name": "NameChild2",
"code": "aitq",
"order": 30,
},
]}]}]}
names = []
function iterator (obj, namesArr){
Object.keys(obj).forEach(key => {
if(key === "name") {
namesArr.push(obj[key])
} else if(typeof obj[key] === "object") {
iterator(obj[key][0], names)
}
})
}
iterator(data.payload[0], names)
console.log(names)
if the api result structure is strongly type and will not change u can access the child payload name by this line
console.log(JSON.stringify(obj.payload[0].childsOfPayload[0].name));
console.log(JSON.stringify(obj.payload[0].childsOfPayload[0].childsofChildOfPayload[0].name));
How would I be able to nest json object if the parent and its children was given as a property.
The data looks like:
"1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"children": [2, 4, 6],
"posts":[
{ "id": "1", "name": "item1" },
{ "id": "2", "name": "item2" },
{ "id": "3", "name": "item3" }
]
},
"2": {
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"children": null,
"posts":[
{ "id": "4", "name": "item4" }
]
},
"3": {
"id": 3,
"name": "bazz",
"parent": null,
"root": 3,
"children": [5, 7],
"posts":[
{ "id": "5", "name": "item5" },
{ "id": "6", "name": "item6" }
]
},
....
A simple groupby using lodash won't do it.
var group = _.groupBy(data, 'parent');
Here is a fiddle:
http://jsfiddle.net/tzugzo8a/1/
The context of question is a nested categories with subcategories, and categories can have categories and posts in them.
Basically I don't want to have a different property for children and posts, since they are all children of a parent.
Desired output
"1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"isCategory": true,
"children": [
{
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"isCategory": true,
"children": null
},
{ "id": "1", "name": "item1", isCategory: false },
{ "id": "2", "name": "item2", isCategory: false },
{ "id": "3", "name": "item3", isCategory: false }
]
...
}
This is my take on the question (fiddle):
var data = getData();
var group = getTree(data);
console.log(group);
function getTree(flat) {
return _.reduce(flat, function (treeObj, item, prop, flatTree) {
var children = _.map(item.children, function (childId) {
return _.set(flatTree[childId], 'isCategory', true);
}).concat(_.map(item.items, function(item) {
return _.set(item, 'isCategory', false);
}));
item.children = !!children.length ? children : null;
delete item.items;
item.parent === null && (treeObj[prop] = item);
return treeObj;
}, {});
}
Take a look on the updated fiddle:
var data = getData();
_.keys(data).forEach(function(id){
var element = data[id];
if (element.children === null){
element.children = [];
}
element.isCategory = true;
element.items.forEach(function(item){
item.isCategory = false;
})
});
_.keys(data).forEach(function(id){
var element = data[id];
element.children = element.children.map(function(childId){
return data[childId];
}).concat(element.items);
});
_.keys(data).forEach(function(id){
delete data[id].items;
});
console.log(JSON.stringify(_.findWhere(_.values(data), {'parent': null})));