Remove json object key value using angular - javascript

I have json response and I want to remove few object key values from it and store the edited response on other part so that I can use again.
I know by using simple javascript, but I don't have any idea in angularjs.
Json response
{
"$id": "1",
"XYZ": [],
"ABC": [
{
"$id": "41",
"ID": 1,
"Order": 0,
"Delay": 0,
"Name": "abc",
"Count": "9",
"Storage": 3,
"Groups": []
}
],
"Projected": 2019
}
Now from this Json file I want to filter out
"$id": "41","ID": 1,"Order": 0,
"Delay": 0, "Groups": [], "Name": "abc"
So my new json structure will be like this which I want to store:
{
"$id": "1",
"XYZ": [],
"ABC": [
{
"Count": "9",
"Storage": 3
}
],
"Projected": 2019
}
Any method to achieve ?

You don't need some magic angular stuff. You can just use plain old JavaScript.
My apporach iterates through all the items in the ABC array and deletes all properties defined in the props array. Note, that this actively modifies the ABC array items.
const obj = {
"$id": "1",
"XYZ": [],
"ABC": [
{
"$id": "41",
"ID": 1,
"Order": 0,
"Delay": 0,
"Name": "abc",
"Count": "9",
"Storage": 3,
"Groups": []
}
],
"Projected": 2019
}
// Now from this Json file I want to filter out
const props = ["$id", "ID", "Order", "Delay", "Groups", "Name"];
props.forEach(prop => {
obj.ABC.forEach(abc => {
delete abc[prop];
});
});
console.log(obj);

An alternative to the other solutions.
If we have a variable called json.
This method is simple
let len = json.ABC.length;
for (let i=0;i<len;i++){
delete json.ABC[i].$id;
delete json.ABC[i].ID;
delete json.ABC[i].Order;
delete json.ABC[i].Delay;
delete json.ABC[i].Groups;
delete json.ABC[i].Name;
}

try this
let json = {
"$id": "1",
"XYZ": [],
"ABC": [
{
"$id": "41",
"ID": 1,
"Order": 0,
"Delay": 0,
"Name": "abc",
"Count": "9",
"Storage": 3,
"Groups": []
}
],
"Projected": 2019
};
json["ABC"] = json["ABC"].map(obj => ({
"Count": obj["Count"],
"Storage": obj["Storage"]
}));
// or dynamic way
let keepkeys = ["Storage", "Count"];
json["ABC"] = json["ABC"].map(obj => {
let newObj = {};
keepkeys.forEach(key => newObj[key] = obj[key]);
return newObj;
});
console.log(json)

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; }

Accessing a specific key in JSON?

I'm trying to access the "title" section (key?) of this JSON object using NodeJS. I can return the entire object, but every time I try to access the key, undefined is returned.
[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
],
[
{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}
],
[
{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}
],
[
{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}
],
[
{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}
]
]
NodeJS
const fs = require('fs')
fs.readFile('./data/links.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[link.url]))
})
I've tried for loops and indexing that way but I haven't been able to get anything out of it.
You have 2 arrays, either loop over both of them or access it using index
let data =[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
]
]
data.map(link=> console.log(link[0].url))
Your json is array of array objects, you need to access all arrays by index, you can use flatMap and map methods.
var data = [
[{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}],
[{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}],
[{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}],
[{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}],
[{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}],
[{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}]
];
console.log(data.flatMap(i=>i.map(f=>f.url)))
Your current code is trying to access an undefined object property.
Solution:
Replace the link[link.url] for link[0].url. So that the full line is
console.log(data.map(link => link[0].url))
Or if you want the titles:
console.log(data.map(link => link[0].title))
console.log(
data.flat().map(link=>link.url)
);
console.log(
data.map(item=>item[0].url)
);
From what I see your JSON file holds an array of arrays and each nested array contains one object. Therefore data.map(link => link[0].title) should return array of titles
You have an array of arrays and each one with just one position. For the code you posted you're just missing the index of each element.
If you change your code to this you'll get the array with the URL's you're looking for
fs.readFile('./example.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[0].url))
})
Happy coding ;)!

How to get Key and Value from JSON object in Javascript(Postman)

I have a JSON object like this, I wanna access the list array elements with key and value in postman.
{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}
How to separate it as Key and Value in Javascript like,
Key: id,name,mobileNo,address,city,..
Value: 53,Sonu,6543213456,Greeny Pathway,NewYork,....
First remove comma from line : "qty": null, otherwise it will cause error in json parsing.
var resultJSON = `{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}`;
var result = $.parseJSON(resultJSON);
var myList = result.data.list[0];
$.each(myList, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use below codes:
const keys = Object.keys(jsonObject);
const values = Object.values(jsonObject);
But your JSON object is deep, you should flatten it and then use keys and values of Object to make them separate.
You can get using key and value separately in a array.
var a = {
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null,
}
]
},
"success": true,
"message": ""
}
var keyval = Object.keys(a.data.list[0])
console.log(keyval)
var values = Object.values(a.data.list[0])
console.log(values)
JSON objects are key value pair you cannot get the keys and values in object form as you desire but you can get both in form of arrays from this code
var key = []
var values = []
list.map(function(l){ keys = Object.getOwnPropertyNames(l);
keys.map(function(key) {values.push(l[key]);})})
Finally this works for me!(In Postman Script)
var resdata = JSON.parse(responseBody);
console.log(resdata);
key = Object.keys(resdata.data.list[0]);
console.log(key);
value =Object.values(resdata.data.list[0]);
console.log(value);

Fetch all the nodes & child nodes inside json including nodes inside array in javascript

Is there a way to read all the nodes & child nodes in a json
for example :
var json_1 = {
"_id": new ObjectID("58bfb7f924bd630dbc7edd31"),
"FirstArray": [],
"Data": [
{
"id": "589cad2ff5fd3d7891f01108",
"modelName": "bbbb",
"modelVersion": "1",
"sequence": "11111",
"aaaaaa": "12345",
"values": [
{
"Zeroth": "67890",
"First": "A",
"Second": "A",
"Third": "AAC",
"Forth": 2,
"Fifth": 239.804,
"Sixth": "A",
"Seventh": "A",
"Eighth": "2017-02-03T21:53:45.000Z",
"Ninth": "Test",
"Tenth": "Test"
}
],
"Date": "2017-02-03T21:53Z"
}
]
}
I'd like to fetch all the keys in the above json and store it in a array.

Categories