Exploring Javascript object properties in an array and matching them against a specific value

Can someone provide a clear explanation of my question using an example? I have an array of objects structured like this:

[{a:"a",b:"",c:"c"}, {a:"a",b:"b",c:""}, {a:"",b:"b",c:"c"}, {d:""} ]
and [a,b]. Initially, I need to verify that the objects in the first array contain the properties from the second array, and then check if those properties are empty strings or undefined. If they are, I want to set them to "something". The final result should appear as follows:
[{a:"a",b:"something",c:"c"}, {a:"a",b:"b",c:""}, {a:"something", b:"b",c:"c"}, {a:"something", b:"something", d:""} ]
Please note that while I currently have a functional code, it is not very aesthetically pleasing and I am looking for a more elegant approach.

Answer №1

If you need a unique collection of keys and want to map values for new entries, here's a solution:

const 
    array = [{ a: "a", b: "", c: "c" }, { a: "a", b: "b", c: "" }, { a: "", b: "b", c: "c" }, { d: "" }],
    keys = ['a', 'b'],
    result = array.map(obj => Object.fromEntries(
        [...new Set([...Object.keys(obj), ...keys])].map(key => [key, keys.includes(key) ? obj[key] || 'something' : obj[key]])
    ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Alternatively, here's another way to achieve this without using Set:

const 
    array = [{ a: "a", b: "", c: "c" }, { a: "a", b: "b", c: "" }, { a: "", b: "b", c: "c" }, { d: "" }],
    keys = ['a', 'b'],
    result = array.map(obj => Object.assign(
        {},
        obj,
        ...keys.map(k => ({ [k]: obj[k] || 'something' }))
    ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

let arr1 = [{a:"a",b:"",c:"c"}, {a:"a",b:"b",c:""}, {a:"",b:"b",c:"c"}, {d:""} ];
let arr2 = ['a','b'];

for (let item of arr1) {
    for (let keyItem of arr2) {
        if (arr2.includes(keyItem) && !item[keyItem]) {
            item[keyItem] = 'Something';
        }
    }
}
console.log('arr1 = ' + JSON.stringify(arr1));

Answer №3

Verify that the elements in the initial array contain all the attributes found in the second array

  1. Iterate through each element in the "first" Array
  2. Go through each key in the "second" Array
  3. Ensure that every key is included at least once within the values of the element

Determine whether any of them are blank strings (or undefined) and replace them with a placeholder like "something"

  1. Iterate through each element in the "first" Array
  2. Examine each key/value pair within the element
  3. If any of the values are empty Strings or undefined, update the value to be "something"

const arr = [{a:"a",b:"",c:"c"}, {a:"a",b:"b",c:""}, {a:"",b:"b",c:"c"}, {d:""}];
const required = ["a", "b"];
const replacement = "something";

const hasRequired = arr.every(e => required.every(req => Object.values(e).includes(req)));

const transformed = arr.map(e => {
  return Object.entries(e).reduce((res, [k, v]) => {
    if (v === "" || v === undefined) {
      e[k] = replacement;
    }

    return res;
  }, e);
});

console.log(hasRequired);
console.log(transformed);

Answer №4

One clever trick we can use is leveraging the falsy nature of empty strings and undefined.

While there are more concise methods available, here's one approach you could take. Loop through each object in the array, check the specified keys, and assign them a value of 'something' if they are falsy; otherwise, keep their current value.

const objects = [{a:'a',b:'',c:'c'}, {a:'a',b:'b',c:''}, {a:'',b:'b',c:'c'}, {d:''}];
const keys = ['a', 'b'];

objects.map(o => {
  for (const key of keys) {
    o[key] = o[key] || 'something';
  }
  return o;
});

Just be cautious if your values might include false, 0, NaN, etc., as those will require specific validation.

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

picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map. My goal is to be able ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

What is the best way to ensure that a mongoose .exec() callback has completed before checking the response object in express?

I am currently developing an application that utilizes Express, Mongoose, and Jest for testing. In order to test my application, I have set up a mongodb in local memory for testing purposes. However, I am facing an issue in some of my tests where the callb ...

What is the best way to eliminate any extra spaces from a string using typescript?

Currently in my Angular 5 project, I am encountering an issue with using the .trim() function in TypeScript on a string. Despite implementing it as shown below, no whitespace is being removed and also there are no error messages appearing: this.maintabinf ...

Utilizing jQuery to efficiently chunk JSON data through AJAX calls

Is there a way to efficiently handle the retrieval of large amounts of JSON data through an ajax request? I am looking for a jQuery or JavaScript function that can assist with "chunking" the data. For example, I would like the ability to continuously rece ...

Using JavaScript to delete the initial option from a dropdown menu

Below is the code snippet: <select id="List" name="UserType" onChange ="hide"> <option value="0" disabled="disabled" selected="selected">User Type</option> <option value="1" onclick="hide">Administrator</option> ...

Exploring the testing capabilities of Angular JS in conjunction with third-party libraries such as

When testing an angular controller that utilizes an external library like Google Analytics event tracking, how can you approach it? For instance: $scope.showVolumn = function() { ga('send', { 'hitType': 'event', ...

When working with the async setup() method in Vue3 with router-view, I encountered a perplexing issue

After implementing async setup () in Vue 3, I noticed that my component was no longer visible. Searching for a solution led me to this post: why i got blank when use async setup() in Vue3. While the suggested fix resolved the initial issue, I encountered a ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...

Internet Explorer is surprisingly accurate when it comes to Number.prototype.toFixed functionality

Imagine this scenario: var x = 2.175; console.log(x.toFixed(2)); // 2.17 It may seem surprising, but it's actually expected behavior. The Number literal 2.175 is stored in memory slightly less than the actual value due to IEEE-754 rules. This can b ...

Create an animated A-frame box that moves randomly within a designated space

Looking to add some movement to my A-frame scene with a random box animation. I want to utilize the animation property to make an entity move randomly within a specified area. The goal is to have a box animate to a random position within coordinates rang ...

How can you modify the encapsulation of a third-party component in an Angular application?

Utilizing AngularElements with native encapsulation allows bs4 components to be used in a bs3 project. For example: @Component({ selector: 'app-my-button', templateUrl: './my-button.component.html', encapsulation: ViewEncapsulati ...

Limit not reached by substring function

When the character limit exceeds 20 characters, the substring function extracts the first 20 characters typed in the input. It replaces any additional characters that are entered after reaching the max limit of 20. In my program, however, I am able to con ...

What causes my page to refresh every time I click on a blank link?

I have a link that looks like this: <a hreflang="15" class="comment-show-link" href="">View/hide comments</a> Afterwards, I use the following code to toggle the visibility of the content: $('.comment-show-link').click(function(e) { ...

Chrome Error Encountered When Using Facebook Sharer.php

Trying to incorporate the sharer button into my Facebook app. It's working fine on all browsers except Chrome. docs.google.com/open?id=0B4wxEQ6Do659WmcwdkN5VlFDZ2s After checking tools->javascript console, I noticed a warning: [blocked] The pag ...

Obtaining targeted information from JSON using JavaScript

Extracting specific data from a JSON object can be challenging, especially if you are new to JavaScript. Below is an example of JSON data containing various fields: {"Date":"2021-01-31........ to ....10.9,"windDir":"SSE"} ...

Looking to locate an array within a schema using its unique identifier

const FormFieldsSchema = new Schema({ formName: { type: String, required: true }, fields: [ { fieldLabel: { type: String, required: true }, inputData: [{ type: mongoose.Schema.ObjectId, re ...

Retrieve a file from an AWS S3 bucket using AngularJS

Currently utilizing angularjs. I am in need of incorporating a download feature. <button class="btn btn-labeled btn-info" title="download"> <a href="link provided by s3" download="downloaded">Download</a> </button> I have ...

Enhancing Bootstrap UI Typeahead to Display Multiple Fields in Results List

Having encountered the same issue as described in this question: Bootstrap-UI Typeahead display more than one property in results list? I made adjustments to the Plunker provided in the answer to fit my requirements: http://plnkr.co/edit/FdkvCUUD3ob7dt2 ...

Consolidate JavaScript files into a single file using phpStorm

My goal with phpStorm is to consolidate multiple JavaScript files into a single one. To achieve this, I have integrated the closure compiler and set up the file watcher to minify each individual JavaScript file. Now my aim is to merge all of these JavaScr ...