Add a property into a JSON object JS - javascript

I have this JSON:
{
"id": 10,
"name": "Color test2",
"seed_id": 1,
"season_id": 2,
"description": null,
"work_schedule_type_id": 2,
"color": "#00A946",
"active": false,
"starred": true,
"phases": [{
"id": 2,
"name": "Phase2",
"work_schedule_type_id": 2,
"phase_color": "#343434",
"phase_order_of_operations": 1,
"description": "TEST PHASE TYPE2",
"isExpanded": false,
"$$hashKey": "object:1387"
}]
}
I need add a property tasks for each phase in phases. How I can do this?

angular.forEach(obj.phases, function(item) { item.tasks = your_val } );

This approach adds the tasks from an Array.
var obj = {
"id": 10,
"name": "Color test2",
"seed_id": 1,
"season_id": 2,
"description": null,
"work_schedule_type_id": 2,
"color": "#00A946",
"active": false,
"starred": true,
"phases": [{
"id": 2,
"name": "Phase2",
"work_schedule_type_id": 2,
"phase_color": "#343434",
"phase_order_of_operations": 1,
"description": "TEST PHASE TYPE2",
"isExpanded": false,
"$$hashKey": "object:1387"
}]
}
var tasks = ["Task1", "Task2"];
obj.phases.forEach(p => p.tasks = tasks);
console.log(obj.phases);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Assuming your JSON object is named json, the code would look something like this:
for (phase of json.phases) {
phase.task = "somevalue";
}

Related

Convert array of objects inside in object into array of properties

I have an Object which is having some properties like this:
obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
I want covert the array of objects (operationIds and ratingIds) inside the object to array of properties, I'm receiving this object and I want to apply the change on it and supply another method so it should look like this:
obj1={
"id": 2,
"description": "",
"operationIds": [
1
],
"ratingIds": [
1,
4,
8
],
"timestamp": "AAAAAAAGJ6c=",
"estimatedUtilReconciliationApplies": true
}
I was able to do it but in a verry ugly way, is there a more simple and clear way to accomplish this ?
let x = {...obj} as any;
let ar1 = x.operationIds;
const arr1= ar1.map(function (obj) {
return obj.id;
});
let ar2 = x.ratingIds;
const arr2= ar2.map(function (obj) {
return obj.id;
});
x.operatingEnvironmentIds = arr1;
x.thrustRatingIds = arr2;
You can use spread operator and map
let obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
console.log({
...obj1,
operationIds:obj1.operationIds.map(elem => elem.id),
ratingIds:obj1.ratingIds.map(elem => elem.id),
})
And as a function
let obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
let transform = (obj) => {
return({
...obj,
operationIds:obj.operationIds.map(elem => elem.id),
ratingIds:obj.ratingIds.map(elem => elem.id),
})
}
let transformed = transform(obj1)
console.log(transformed)
We loop the array and use the Object.assign() method to convert an array of objects to a single object. This merges each object into a single resultant object.
The Object.assign() method also merges the properties of one or more objects into a single object.

Replacing two objects in an array

I am trying to develop a dynamic DraggableFlatList with react native redux, where the updated array from onDragEnd is dispatched to the store. Hence I am trying to create a function where I use the "from" and "to" parameters from the return object from onDragEnd to alter a new array before dispatch. As an example, in the object below, I work with three items, that are objects from the array:
Object {
"data": Array [
Object {
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
},
Object {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
},
Object {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
},
],
"from": 2,
"to": 1,
}
Here I would like the object with the description "two" to change place with the object with the description "one." The keys don't matter because I give them new keys when I render during render.
The function that is doing the replacement looks like this so far:
const dragComplete = (item) => {
let itemArray = item.data;
// from object is going to be replaced with to object and visa vreca
let indexFrom = item.from;
let indexTo = item.to;
let objMovesFrom = itemArray[indexFrom];
let objMovesTo = itemArray[indexTo];
let sortedArray = itemArray;
console.log('Object moves from : ' + objMovesFrom.description);
console.log('Obejct moves to : ' + objMovesTo.description);
sortedArray.map((task, i) => {
if ((i = indexFrom)) {
sortedArray.splice(indexFrom, 1, objMovesTo);
}
if ((i = indexTo)) {
sortedArray.splice(indexTo, 1, objMovesFrom);
}
});
console.log(item);
//dispatch(setTaskList(item.data));
};
I haven't figured to make any sense of it yet...
Thx for the helpful answers!
How about just simply swapping items?..
const dragComplete = item => {
const {
from: sourceIndex,
to: targetIndex,
data: dragList,
} = item;
// // shallow `item.data` copy for a non mutating approach.
// const swapList = Array.from(dragList);
const dragItem = dragList[sourceIndex]; // swapList[sourceIndex];
const swapItem = dragList[targetIndex]; // swapList[targetIndex];
// simply swap items.
// actively mutate `item.data`. // // `item.data` remains unmutated.
dragList[targetIndex] = dragItem; // swapList[targetIndex] = dragItem;
dragList[sourceIndex] = swapItem; // swapList[sourceIndex] = swapItem;
console.log('Object moves from : ' + dragItem.description);
console.log('Object moves to : ' + swapItem.description);
// return swapList;
};
const sample = {
"data": [{
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
}, {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
}, {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
}],
"from": 2,
"to": 1,
};
console.log({ data: sample.data });
dragComplete(sample);
console.log({ data: sample.data });
.as-console-wrapper { min-height: 100%!important; top: 0; }

Mongoose Sorting , .sort() queries output is not as expected

My code for sorting episodes in ascending order using episodeNo is
const episodes = await Episode.find({anime: animeId}).sort({episodeNo: 1});
I think it should sort like 1, 2, 3, 4 but it's sorting like 1, 10, 11, 2, 3.
the JSON response is
"id": "607dc50dc21368000414b378",
"episodeNo": 1,
"subtitle": false
},
{
"id": "607dc50dc21368000414b381",
"episodeNo": 10,
"subtitle": false
},
{
"id": "607dc50dc21368000414b382",
"episodeNo": 11,
"subtitle": false
},
{
"id": "607dc50dc21368000414b383",
"episodeNo": 12,
"subtitle": false
},
{
"id": "607dc50dc21368000414b379",
"episodeNo": 2,
"subtitle": false
}

Postman : How to assert all array elements exist in other array?

I'm asserting for elements in array1 does exist in array2 or not, below are the array samples,
var array1 = [
{
"name": "appe",
"loc": "war",
"order": 5,
"neck": "NO",
"end": false
},
{
"name": "con",
"loc": "conve",
"order": 15,
"neck": "NO",
"end": true
}]
var array2 = [{"neck":"NO"
"end":true,
"loc":"conve",
"name":"con",
"order":15
}]
code I tried -
const lodash = require("lodash");
for(var i = 0; i < array2.length; i++ )
{
tests['response json contain Data'] = lodash._.has(points, array2[i]);
//pm.expect(array2[i]).to.be.oneOf(array1);
}
error I get -
response json contain Data | AssertionError: expected false to be truthy
EDIT
after trying another attempt2 -
pm.expect(array2[i]).to.be.oneOf(array1);
error -
AssertionError | expected { Object (name, loc, ...) } to be one of [ Array(20) ]
attempt3 -
pm.expect(array1).to.deep.equal(array2);
error -
AssertionError | expected [ Array(20) ] to deeply equal [ Array(18) ]
what I'm doing wrong?. what I want is if any one element in array2 is not in array1 it should fail.
Thanks
Chai assertion Library is included by Postman by default in its application. So you need to use the to.deep.equal. It will compare nested arrays as well as nested objects.
SOLUTION:
pm.test("verify two objects", function () {
var array1 = [{
"name": "appe",
"loc": "war",
"order": 5,
"neck": "NO",
"end": false
},
{
"name": "con",
"loc": "conve",
"order": 15,
"neck": "NO",
"end": true
}];
var array2 = [{
"neck": "NO",
"end": true,
"loc": "conve",
"name": "con",
"order": 15
},
{
"neck": "NOo",
"end": true,
"loc": "conve",
"name": "con",
"order": 15
}];
pm.expect(array1).to.deep.equal(array2); // Failed
pm.expect(array1).to.deep.equal(array1); // Passed
});
var array1 = [{
"name": "appe",
"loc": "war",
"order": 5,
"neck": "NO",
"end": false
},
{
"name": "con",
"loc": "conve",
"order": 15,
"neck": "NO",
"end": true
}
]
var array2 = [{
"neck": "NO",
"end": true,
"loc": "conve",
"name": "con",
"order": 15
}]
array2.forEach( item => {
if ( !array1.includes(item)){
throw 'doesn\'t include'
}
})
what I want is if any one element in array2 is not in array1 it should fail
var array1 = [{
"name": "appe",
"loc": "war",
"order": 5,
"neck": "NO",
"end": false
},
{
"name": "con",
"loc": "conve",
"order": 15,
"neck": "NO",
"end": true
}
]
var array2 = [{
"neck": "NO",
"end": true,
"loc": "conve",
"name": "con",
"order": 15
}, {
"neck": "NOo",
"end": true,
"loc": "conve",
"name": "con",
"order": 15
}];
// Finds at least one object on array2 which is not in array1.
// The function some finds at least one according to the
// result of findIndex which is using a handler who executes
// the function every.
// The function every, basically, compares every key-value
// between array2 and array1.
let result = array2.some(o => array1.findIndex(ao => Object.entries(o).every(([key, value]) => ao[key] === value)) === -1);
console.log(result); // Returns true because one element is not in array1

How to normalize a nested reponse using normalizr

I would like to normalise a nested JSON data response which I get from the API. The data response contains agents who belong to multiple shifts. The relation between the entities are many-to-many association since, A shift can many agents and an agent can belong to many shifts. So I came across this normalizr utility where I tried to normalize the date to this form so I would be able parse this easier.
I tried to normalize to this form
{
entities : {
shifts:[{...}],
agents:[{...}]
}
}
import { normalize, schema } from 'normalizr';
import stubData from './stubData';
const agent = new schema.Entity('agents', {});
const day_agents = new schema.Entity('day_agents', {
agents: [agent]
});
const shift = new schema.Entity('shifts', {
day_agents
});
const normalizedData = normalize(stubData, shift);
stubData:
"shifts": [{
"id": 1,
"name": "Shift 1",
"start_time": "9:00",
"end_time": "5:00",
"day_agents": {
"10/4/2019": {
"leaves": 1,
"agents": [
{
"id": 1,
"name": "a",
"email": "a#b.co",
"group_id": 1,
"Leave": false
},
{
"id": 2,
"name": "b",
"email": "b#b.co",
"group_id": 1,
"Leave": false
}
]
},
"11/4/2019": {
"leaves": 1,
"agents": [{
"id": 4,
"name": "c",
"email": "c#c.co",
"group_id": 2,
"Leave": true
},
{
"id": 5,
"name": "d",
"email": "d#d.co",
"group_id": 2,
"Leave": false
}
]
}
}
}]

Categories