Remove a field from an object using Lodash - javascript

I want to send a data attribute to an API server only if the method is add, if it's delete, I don't don't want to send my data.
I have
var body =
{
id: 1,
method: method,
params: [
{
data: {
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
},
url: `/url/anything`
}
],
session: session,
verbose: 1
};
I tried
if(method == 'delete') {
_.pick(body.params[0], ['data']);
}
I also tried
if(method == 'delete') {
_.pick(body.params[0],'data');
}
For some reason, I still see that I still sending the data.
How would one go about debugging this?

if you take a look at lodash pick documentation you'll see that it doesn't change the source object instead its create a new object from the source object properties and returns the new object , if you want to remove the data property from the source object , you can use the unset method from lodash which removes a property from an object or a set of props ,
also you can use the delete operator

use _.assign:
var body =
{
id: 1,
method,
params: [
_.assign({url: `/url/anything`}, method === 'delete'
? null
: {
data: {
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
}
)
],
session,
verbose: 1
};

You may need to do this.
if(method === 'delete') {
body.params[0].data = undefined;
}
In this case, we delete all of the content of data by assign undefined.

Related

Convert object containing objects to array containing objects

I have a JSON object that will sometimes be an object (a single instance) and sometimes be an array (multiple instances of the object). I need to write an if statement that basically says if this section of JSON is an object, wrap it in an array containing that single object, and if it's an array containing multiple objects, return that array. In either instance I'm returning an array containing either 1 or multiple objects.
Here is what the JSON looks like when it is NOT an array.
"link": {
"values": {
"key1": "value1",
...
"key8": "value8"
},
"key9": "value9"
}
And it should look like this when it's an array:
"link": [{
"values": {
"key1": "value1",
...
"key8": "value8",
},
"key9": "value9"
}]
EDIT -----------------------------
This is what I've written so far that is producing the type error I'm experiencing.
const isLinkArray = sections.values;
isLinkArray.link = Array.isArray(isLinkArray.link) ? isLinkArray.link : [isLinkArray.link];
EDIT 2 ---------------------------
The final answer ended up being almost identical to Kinglish' answer, so I figured I would post it here. The issue I ran into was that the JSON right above 'link' was also an array and that was causing the typescript error.
const sectionsWithLinkArray = sections.map((section) => {
  return {
    values: {
      ...section.values,
      link: !Array.isArray(section.values.link) ? [section.values.link] : section.values.link,
    },
  };
});
You can use Array.isArray to check, then convert
let data = {
"link": {
"values": {
"key1": "value1",
"key8": "value8"
},
"key9": "value9"
}
}
data.link = Array.isArray(data.link) ? data.link : [data.link];
console.log(data)
This can be done by writing a simple function that checks if it's an array.
const returnArray = (value) => {
if (Array.isArray(value) {
return value;
}
return
}
updated the answer of #Kinglish to typescript one because you cannot change types of defined value as it giving error for this either simply ignore the typescript or define types that simply accept link in object and array of object or just created new variable that expect a link in the array and wrap it inside data by simply doing this:
const data = {
link: {
values: {
key1: 'value1',
key8: 'value8',
},
key9: 'value9',
},
};
// This is the type of data you can't change it by default and it doesn't expect array of object of `link`.
// const data: {
// link: {
// values: {
// key1: string;
// key8: string;
// };
// key9: string;
// };
// };
const linkArray = { link: Array.isArray(data.link) ? data.link : [data.link] };
// Now this is the type of linkArray that expect array of object of `link`
// const linkArray: {
// link: {
// values: {
// key1: string;
// key8: string;
// };
// key9: string;
// }[];
// };
console.log('data', data);
console.log('linkArray', linkArray);

Normalise the JSON where Array as an value in javascript

I was trying to normalize a very deeply nested JSON which contains all possible ways JSON can be created. A part of JSON can be seen in below code snippet.
What is my end goal
I am converting the nested JSON into a simple JS object like below
{
key1: value,
key2: value,
...
}
Problem i faced with the below solution is that when it comes to Objects with values as array
i failed to find a way to see its key values.
if you run below code
key4,key5, key6 wont get displayed with the console.log only its value gets printed.
key1 -- values
key2 -- values
key3 -- value3
0 --
0 -- some_value
Code snippet
const req = {
request: {
results: {
key1: 'values',
results: [
{
key2: 'values',
},
],
},
params: {
key3: 'value3',
query: {
key4: [''],
key5: ['123456'],
key6: ['some_value'],
},
},
},
};
function normaliseJSON(obj) {
for (let k in obj) {
if (obj[k] instanceof Object) {
normaliseJSON(obj[k]);
} else {
console.log(`${k} -- ${obj[k]}`);
}
}
}
normaliseJSON(req);
Is there any way to get the keys of key4,5,6 ?
also open to any other solution to normalise such JSON
The reason your recursion goes inside the array is since ['123456'] instanceof Object is true in javascript (typeof(['asd']) also gives "object"). To check if something is an array have to check with Array.isArray(something)
In template literals when you try to embed an array eg ...${['123456']} in the end it will show as ...123456 without the brackets. Therefore in situation of Arrays need to JSON.stringify(arr)
There may be better ways of doing this but I created a function called arrayHasObject which checks if an array has object elements. This was to catch the inner results array and ignore key4,key5 and key6.
The recursion will happen if obj[k] is an object and not an array or if obj[k] is an array and it has an object element.
Since recursion is hard to visualize I recommend https://pythontutor.com/ . It is mostly for Python but works for JS as well. It can help you visualize these things and to find where things go wrong
Ofcourse the way I have written it will break if something like key4: [{a:'abc'}] since arrayHasObject gives true for this. Maybe will need to change the function accordingly.
function arrayHasObject(arr) {
return arr.some((x) => typeof(x)==='object' && !Array.isArray(x))
}
const req = {
request: {
results: {
key1: 'values',
results: [
{
key2: 'values',
},
],
},
params: {
key3: 'value3',
query: {
key4: [''],
key5: ['123456'],
key6: ['some_value'],
},
},
},
};
function normaliseJSON(obj) {
for (let k in obj) {
if ((obj[k] instanceof Object && !Array.isArray(obj[k])) || (Array.isArray(obj[k]) && arrayHasObject(obj[k]))) {
normaliseJSON(obj[k]);
} else {
if (Array.isArray(obj[k])){
console.log(`${k} -- ${JSON.stringify(obj[k])}`);
}
else{
console.log(`${k} -- ${obj[k]}`);
}
}
}
}
normaliseJSON(req);

How to insert json values into object

I have a predefined object (SampleObject) like this:
{
ID: "",
Name: "",
URL: "",
prevName: "",
Code: "",
}
And I want to insert the below json object values(values only):
var object =
{
"Sample" : {
"Data" : {
"ID" : "12345",
"Name" : "SampleName: Name",
"URL" : "www.google.com",
"prevName" : "phones",
"Code" : "USD"
}
}
into the above predefined object. How do I do that?
You can just use a for in loop and set the value checking if the key is present in the object or not.
Check if the property is present on the emptyObject, and then copy that over to it.
for (var key in pageInfo) {
var value = pageInfo[key];
if (obj.hasOwnProperty(key)) {
obj[key] = value;
}
}
Code Pen
It is an object. There is no reason to use push or another method.
Simply take your defined object pageObject.page and assign a new key value pair with literal syntax.
pageObject.page['pageInfo'] = predefinedObject
or in more common syntax
pageObject.page.pageInfo = predefinedObject
Use the following code below the JSON Object
var digitalData= {page:{pageInfo:''}};
digitalData.page.pageInfo = pageObject.page.pageInfo;
console.log(digitalData.page.pageInfo);

Remove specified element from associated array

Hi I am looking for ways to delete the elements from associate array.
I need to remove values like null and '' while in the loop. But I cant because I know that I will need to identify and the build array to store, Then use elements in the new array to seek and remove them.
var storeData3 = [
{ 'key' : 'value1' },
{ 'key' : 'value2' },
{ 'key' : 'value3' },
{ 'key' : null },
{ 'key' : '' },
{ 'key' : 'value10'}
];
Try this:-
Using Array.filter to get the data after omitting unwanted data.
var result= storeData3
.filter(function(val){
return (val.key != '' && val.key != null)});
.filter()
Fiddle

How can I filter JSON when searching for a sub part of a string?

I'd like to filter a JSON object client-side. Until then I did it server side with a:
SELECT * FROM table WHERE row1, row2, row3 LIKE %search%
I want to do the same thing client side with a JSON object.
For example I could have this JSON object :
[{'Key1' : 'Value1', 'Key2': 'Value2'}
{'Key3': 'Value3', 'Key4': 'Value4'}]
When I use the filter 'ue3' I'd like it to return [{'Key3': 'Value3', 'Key4': 'Value4'}]
"I want to do an all fields search on an array of objects and only return the objects that have part of the search string in one of their fields."
var a = [{'Key1' : 'Value1', 'Key2': 'Value2'},
{'Key3': 'Value3', 'Key4': 'Value4'}];
var b = filterValuePart(a, "ue3");
function filterValuePart(arr, part) {
return arr.filter(function(obj) {
return Object.keys(obj)
.some(function(k) {
return obj[k].indexOf(part) !== -1;
});
});
});
shim, shim, shim
To make it case insensitive:
function filterValuePart(arr, part) {
part = part.toLowerCase();
return arr.filter(function(obj) {
return Object.keys(obj)
.some(function(k) {
return obj[k].toLowerCase().indexOf(part) !== -1;
});
});
});
Supposing you have this JavaScript object :
var array = [
{'Key1' : 'Value1', 'Key2': 'Value2'},
{'Key3': 'Value3', 'Key4': 'Value4'}
];
then you can find objects whose a property value contains a string using
var searched = 'ue3';
var matches = array.filter(function(v) {
for (key in v) {
if (v[key].indexOf(searched)!=-1) return true;
}
return false;
});
var match = matches.length==0 ? null : matches[0];
Note that IE 8 doesn't support filter but this MDN article gives a shim.
#Ping - you can use the javascript lib DefiantJS (http://defiantjs.com). With it, you can do something like this:
var data = [
{
"Key1": "Value1",
"Key2": "Value2"
},
{
"Key3": "Value3",
"Key4": "Value4"
}
].
res = JSON.search( data, '//*[contains(., 'ue3')]' );
console.log( res[0].key3 );
// Value3
Here is a working fiddle:
http://jsfiddle.net/hbi99/s8ZVg/
Notice that the JSON structure is quoted, which as JSON should be.
DefiantJS extends the global object JSON with a method called "search" and with XPath query (which is a standardised query language), it returns matches in an array (empty array if no matches were found).

Categories