Populate an empty value in a key-value pair by using the subsequent value

Replace an empty value in a key-value pair with the first value of the next key.

myitems = {
 'items1': [{first:true, second:false}, {first:true, second:true}],
 'items2': [], //should be filled with {first:true, second:false}
 'items3': [], //should be filled with {first:true, second:false}
 'items4': [{first:true, second:false}, {first:true, second:true}],
 'items5': [{first:false, second:true}],
 'items6': [], //should be filled with {first:true, second:true}
 'items7': [{first:true, second:true}],
}

I attempted the following solution:

Object.entries(myItems).forEach(([key, value], index, values: any) => {
   if (!values[index][1].length && values[index+1] && values[index+1][1].length) {
   myItems[key] = [{...values[index + 1][1][0]}]
 }
})

Answer №1

One possible approach for the specific scenario provided is to implement a solution using a temporary variable called `next`, which would store the most recent next's Object from the Array of `Object.values`. This can be achieved by utilizing either .reduceRight() or .reverse().forEach() method:

const myItems = {
  'items1': [{first:true, second:false}, {first:true, second:true}],
  'items2': [], //needs to be populated with {first:true, second:false}
  'items3': [], //should contain {first:true, second:false}
  'items4': [{first:true, second:false}, {first:true, second:true}],
  'items5': [{first:false, second:true}],
  'items6': [], //requires {first:true, second:true} insertion
  'items7': [{first:true, second:true}],
};


let next;
Object.values(myItems).reverse().forEach((arr, i) => {
  if (!i || arr.length) return next = arr[0];
  arr[0] = {...next};
});

console.log(myItems);

However, it should be noted that this approach may not be the most efficient solution in all cases.

Answer №2

It's important to pay attention to the comments regarding the order of keys in the object. Consider using the reduceRight method for a potential solution:

const myItems = {
  'items1': [{first:false, second:false}, {first:false, second:false}],
  'items2': [], //needs filling with {first:true, second:false}
  'items3': [], //requires filling with {first:true, second:false}
  'items4': [{first:true, second:false}, {first:true, second:true}],
  'items5': [{first:false, second:true}],
  'items6': [], //needs filling with {first:true, second:true}
  'items7': [{first:true, second:true}],
}

const result = Object.entries(myItems).reduceRight( (accumulator, currentValue) => {
  const [key, value] = currentValue;
  if (!value.length) {
    accumulator.unshift([key, [...accumulator[0][1]]]);
  } else {
    accumulator.unshift([key, [...value]]);
  }
  return accumulator;
}, [] );

console.log( JSON.stringify( Object.fromEntries(result), null, 2 ) );

Answer №3

If you take a look at the provided data object, it guarantees the order in which items are processed. To tackle this in TypeScript, here's a solution:

const myItems: Record<string,{first:boolean, second:boolean}[]> = {
 'items1': [{first:true, second:false}, {first:true, second:true}],
 'items2': [], // need to add {first:true, second:false}
 'items3': [], // need to add {first:true, second:false}
 'items4': [{first:true, second:false}, {first:true, second:true}],
 'items5': [{first:false, second:true}],
 'items6': [], // need to add {first:true, second:true}
 'items7': [{first:true, second:true}],
}

const arr: (keyof typeof myItems)[] =[];
for (let k in myItems) arr.push(k);
arr.reverse();
console.log(arr);

let last: {first:boolean, second:boolean} | undefined;
arr.forEach((k,ki)=>{
    if (myItems[k].length===0){
        if (last) myItems[k].push(last);
    }
    else {
        last = myItems[k][0];
    }
});

for (let k in myItems) {
    console.log(k);
    console.log(myItems[k][0]);
}

Explore TypeScript Playground

The resulting order is as follows:

[LOG]: ["items7", "items6", "items5", "items4", "items3", "items2", "items1"] 
[LOG]: "items1" 
[LOG]: {
  "first": true,
  "second": false
} 
[LOG]: "items2" 
[LOG]: {
  "first": true,
  "second": false
} 
[LOG]: ... // more logs for each item

For additional information, refer to MDN documentation on object property orders

According to modern ECMAScript specifications, traversal order of properties within an object is consistent and well-defined. This includes iterating through keys both numerically and alphabetically.

Please note: If the final properties in myItems end up as empty arrays, they will remain so as there is no content to replace them with.

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

Encountering the error "Uncaught reference error: $ is not defined" despite ensuring that scripts are loading in the correct order. However, the scripts work from the

Encountering an Issue: "Uncaught ReferenceError: $ is not defined" Whenever I try to utilize $('#someid') in my custom JavaScript code within an Electron app. All scripts are properly arranged in my HTML file: <script type="text/javascri ...

How to override or redefine a TypeScript class with generics

Presently, I am immersed in a project involving three.js and TypeScript. It has come to my attention that for organizing elements, the Group class is highly recommended. However, I have noticed that the type definitions for Group do not include a feature l ...

Navigating to new location following the final iteration in a loop of asynchronous updates in MongoDB

Currently, I am developing an application using Node/Express/Mongodb/Mongoskin. I am facing an issue with the code responsible for updating a collection of documents: db.collection('invoices').find().toArray(function(err, dbDocs) { if (err) t ...

A guide on how to group by multiple keys and calculate the sum of multiple property values within a JavaScript array using Node.js

Can you suggest the most efficient method to group by multiple keys and calculate the sum of multiple property values in a JavaScript array? For example: [ { Category: "Category 1", Subcategory: "Subcategory 1", Value1: "15&q ...

Utilizing a forwardRef component in TypeScript to handle child elements

Working with @types/react version 16.8.2 and TypeScript version 3.3.1. This forward refs example was taken directly from the React documentation with added type parameters: const FancyButton = React.forwardRef<HTMLButtonElement>((props, ref) => ...

AngularJs does not properly update the scope of a scoped directive when using ng-repeat within itself

The issue arises from calling Directive1 within the same Directive1 using ng-repeat. Although directive11 has a value in scope, when calling the nested directive with a new value, it appears to retain the initial value. I attempted to invoke the same dire ...

AngularJS encounters bad configuration on 'GET' request

I am facing an issue with my API that returns data to AngularJS based on a given ID. When the data is returned as JSON, AngularJS throws a 'badcfg' error, indicating that it could be due to the format of the returned data. I'm struggling to ...

Beginning external plugin in Angular 4 application

Is it possible to incorporate an external plugin into an Angular 4 application? I am looking to utilize the niceScroll plugin for a scrollable div, which is defined within a component. <div class="d-flex" id="scrollable"> <app-threads-list> ...

Combining 2 Observables in nestjs Interceptor: A Step-by-Step Guide

I am currently working on a NestJS interceptor to geolocate an address that is being sent through a REST API. Here is the code snippet: export class PointsInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): O ...

What could be causing the error "Type 'String' cannot be used as an index type" to appear in my TypeScript code?

My JavaScript code contains several associative arrays for fast object access, but I'm struggling to port it to TypeScript. It's clear that my understanding of TypeScript needs improvement. I've searched for solutions and come across sugges ...

Currently in the process of developing an electron application, I encountered an Uncaught Exception error stating: "TypeError: $.ajax is not

I'm currently working on an electron app that interacts with an API endpoint and displays the response on the page. Due to electron's separation of main process and renderer process, I'm using a preload script to facilitate communication bet ...

Learn how to render a single element with multiple child elements within separate `<td>` tags in a table row using React

I'm just starting out with React and I have a code snippet that I'm using to render an HTML table in a component. Is there a more optimized way to achieve this? bodyItems = sorted.map((data) => [ data.employerName, data.sectors.map((sector ...

Combining Two Validation Methods for jQuery Validate Plugin

Seeking advice on how to incorporate custom validation methods from jQuery validate into another method for validating data. Specifically, I have a 'Document ID' field that can accept either CPF or CNPJ (Brazilian documents) and I need to validat ...

What is the best way to display Redis data in express.js?

As a beginner in node.js and express.js, I find myself stuck on a problem that I'm hoping someone can help me solve. I have data stored in Redis. redis 127.0.0.1:6379> hgetall "store1" 1) "apple" 2) "10" 3) "banana" 4) "15" 5) "pear" 6) "20" 7) "n ...

Positioning social media icons directly below the Avatar component

I've been working on aligning my social media icons under the Avatar component. Despite trying multiple methods to center them in the JSS, I haven't had much success. I attempted different approaches but couldn't achieve the desired alignmen ...

Tips for verifying a string date using the Ajax Control Toolkit (CalendarExtender) technology

I have a dilemma with two formatted TextBoxes that receive their text value from a CalendarExtender. I need to validate that the first TextBox is greater than the second one, but the values are coming in as strings rather than dates. Ho ...

The Jquery watermark extension in IE9 is capable of transmitting the watermark as the primary value of the form

I have integrated a plugin into my project. The plugin can be downloaded from this link. However, I am facing an issue where the watermark value is being submitted as the textbox's value in Internet Explorer 9. How can I resolve this problem? Intere ...

Converting Dates to getTime() in AngularJS prior to server transmission

In my form, I am using <input type="datetime-local" ng-bind="course.endDate".. to set a model variable. Before sending the date to the server, I need to convert the date 2015-04-04T22:00:00.000Z to an integer using getTime(). In the controller, I added ...

Experiencing TypeScript error in VSCode while trying to run in Nodejs? Here's how to troubleshoot and resolve

Experimenting with the performance measurement code provided by Nodejs in VSCode has been an interesting challenge for me. I encountered no issues running the code in Nodejs, and it executed smoothly. However, when attempting to run the code in VSCode, er ...

Sending properties to a child component - React Native

My goal is to set the color prop for an icon child component. In this scenario, I am using the <Feather /> icon and need to pass the color prop. Here is my component along with the Feather child component: import { Feather } from '@expo/vector ...