Validate a JSON object key

There are two ways in which we receive JSON strings:

"{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}"

Or

"{"phoneNumber":["0099887765"]}"

We need to convert the JSON string from the first format to the second format.

Is there a way to write a JavaScript code that can determine which JSON string has the "add" key and which one does not?

Answer №1

After parsing the JSON data, you will receive an array with either two objects for the first style or one string entry. Here is the code snippet to handle this:

function processJSON(data) {
    let parsedData = JSON.parse(data);
    
    if (typeof parsedData.phoneNumber[0] === "object") {
        parsedData.phoneNumber = [parsedData.phoneNumber.find(obj => obj.add).add[0]];
    }
    
    console.log(parsedData);
}

Here is a live example of how to use the function:

function processJSON(data) {
    let parsedData = JSON.parse(data);
    
    if (typeof parsedData.phoneNumber[0] === "object") {
        parsedData.phoneNumber = [parsedData.phoneNumber.find(obj => obj.add).add[0]];
    }
    
    console.log(parsedData);
}
    
processJSON('{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]');

processJSON('{"phoneNumber":["0099887765"]}');

If you require an ES5 version, here it is:

function processJSON(data) {
    var parsedData = JSON.parse(data);
    
    if (typeof parsedData.phoneNumber[0] === "object") {
        parsedData.phoneNumber = [parsedData.phoneNumber.find(function(obj) { return obj.add; }).add[0]];
    }
    
    console.log(parsedData);
}

Answer №2

If you're looking to determine whether the property "add" exists in any object within an array, you can utilize the function some. Here is a generic approach:

const json = '{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}';
const data = JSON.parse(json);

function checkForKey(data, { arrayKey, searchKey }) {
  return data[arrayKey].some(obj => obj[searchKey]);
}

const hasAdd = checkForKey(data, {arrayKey: 'phoneNumber', searchKey: 'add' });
console.log(hasAdd);

Answer №3

To achieve this, you can utilize a combination of the for..in loop along with the hasOwnProperty check. Then, make sure to only push the phone numbers that have the 'add' index. I hope this explanation is helpful :)

const result = {'phoneNumber':[]};
let data = '{"phoneNumber":[{"add":["0099844465"],"remove":["0099887769"]},{"add":["0099887765"]}]}'';

const jsonData = JSON.parse(data);
for (var key in jsonData['phoneNumber']) {
        if (jsonData['phoneNumber'][key].hasOwnProperty('add')) {
           result['phoneNumber'].push(jsonData['phoneNumber'][key]['add']);
        }
}

console.log(result);

Answer №4

Start by using the code

let data = JSON.parse('{"contacts":[{"remove":["1234567890"]},{"add":["0987654321"]}]}')
to transform it into an object. Next, loop through the data and extract the values, then add them to a new object.

Answer №5

To determine if 'add' is a top-level property, follow these steps:

if(obj['add']) {....}

If the property exists, the if statement will evaluate to true. If it does not exist, it will return undefined and the if statement will be false.

If you need to check for 'add' in an array of objects, you can apply the same logic using the find method from the array prototype.

phoneNumber.find(obj => obj['add']);

Answer №6

To verify the presence of the add key, you can convert the JSON data into an array:

Converting JSON to Array in JavaScript: A Comprehensive Guide

Once converted, you can easily check if the key exists by simply testing for its undefined status:

if (obj["phonenumber"]["add"] !== undefined) {
    // Key is present
} else {
    // Key is not present
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the variable using Ajax after the content has loaded

I am struggling with the following code snippet: <?php $num=12; ?> <html> <head></head> <body> <div id="test"></div> <script type="text/javascript"> function fetchContent() { var ...

Retrieving a specific item from a sql-array using jOOQ

How do I retrieve an item from an array in JOOQ similar to this SQL query? SELECT (ARRAY_AGG(id))[1] FROM entities; Is there a way to achieve this using JOOQ? dsl().select(arrayAgg(ENTITIES.ID).get(1)).from(ENTITIES).fetch(); Alternatively, can I acces ...

Transferring an array from PHP to JavaScript via an Ajax response

Welcome to my first post on stackoverflow. I usually find answers from existing posts, but this time I'm facing a problem that none of the suggested solutions have been able to fix. Currently, I have a JavaScript function that makes an AJAX request t ...

Print custom jQuery attribute to console or log output

I need help retrieving and displaying a custom jQuery attribute in either an alert or console. Despite attempting to use console.log() to access my custom data attribute, I am unable to see its value appear. The specific value I am trying to display is d ...

Running jQuery in AngularJS partialsHow can I incorporate jQuery into AngularJS partials?

I'm currently leveraging the power of the Angular UI router to divide my web pages into partial views and load them accordingly. However, I've run into an issue where I can't seem to utilize jQuery within these partial views. My approach inv ...

What is the proper way to place a newly added element using absolute positioning?

Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every tim ...

Footer positioned correctly with relative DIV

I find myself in a state of complete confusion. Coding is not exactly my forte, so I suspect I have made a significant error somewhere that is causing the following issue: My goal is to create a sticky footer. The footer does indeed stick to the bottom of ...

Utilizing Cowboy as the HTTP web server for Express JS

Many websites are utilizing Cowboy as the HTTP Web server and Express JS as the Web application server. They typically have their HTTP header set to Cowboy for the server, with the X-Powered-By HTTP header indicating Express. One example is This setup rai ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Guide to using AES-256-CBC encryption in Node.js and decrypting with OpenSSL on a Linux system

Question: Hello there, I am currently facing an issue with decrypting my encoded base64 using a specific command. Here is the command that I am trying to use: echo "base64key" | (openssl enc -AES-256-cbc -d -a -pass "pass:test" -pbkdf2 ...

Unable to navigate to the frame within the Salesforce Lightning interface

Attached below is the screenshot and code that I have used: driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@title,'Deploy Data Set')]"))); <div class="slds-template_iframe slds-card" force-aloha-page_aloha-page=""> ...

`meteor.js and npm both rely on the fs module for file

I'm feeling a bit lost, as I need to use the fs package with Meteor.js framework. Starting from meteor version 0.6 onwards, I know that I should use Npm.require in the following way: var fs = Npm.require('fs'); However, when I try this, a ...

MongoDB is able to retrieve a nested array of objects with a certain property removed from each object. It should be noted that .then() does not function with aggregation

I am a newcomer to mongodb and struggling to find a solution for my specific use case. Here is an example document I am working with: { _id : ObjectId('5rtgwr6gsrtbsr6hsfbsr6bdrfyb'), uuid : 'something', mainArray : [ ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

Unable to render the Google Gauge chart using the provided JSON information

I'm currently facing an issue with implementing Google charts on my website using data from a MySQL database through JSON encoding. Despite ensuring that my JSON encoded data is in the correct format based on various forums, I'm encountering diff ...

Bootstrap not being recognized in AngularJS HTML

I've been working on learning AngularJS, but unfortunately I can't seem to get any Bootstrap themes to show up in my web application. Here is the HTML code for the header that I've been trying: <nav class="navbar navbar-default"> ...

Transmitting JSON data from Stream Analytics to Power BI

https://i.sstatic.net/8gfqD.pngI'm currently working on sending simulated data from kepware to Azure Hub and then to Stream Analytics. The next step would be to send it directly to Power Bi, but it seems like stream analytics is sending an array to Po ...

Troubleshooting Error 400 while fetching JSON data using $http.get method in AngularJS

I keep encountering a 400 error when attempting to fetch the JSON data from the following URL using $http.get. $http.get('https://api.spotify.com/v1/search?q=artist:Owl+City+title:On+The+Wing&type=track&limit=1'). success(function(data) ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...