Guide to updating the key label within an array

I have an array below that needs to be updated with key values changed from Apple fruit to Pizza shop, Orange fruit to Kfc shop, Banana fruit to Mcdonald shop, Mango fruit to fries shop if any of the value pairs exceed 15 characters. If the character count does not exceed 15, the response should remain the same.

For example, "Testing 3" has a value that exceeds 15 characters.

 [
        {
            "key": "Apple fruit",
            "value": "12123124344234234"
        },
        {
            "key": "Orange fruit",
            "value": "234352342332525"
        },
        {
            "key": "Banana fruit",
            "value": "235235235235235235235"
        },
        {
            "key": "Mango fruit",
            "value": "235325235235235"
        }
    ]

My code snippet:

    this.testItem.push({
      key: testlabel,
      value: testvale,
    });
    console.log(this.testItem);

this.testItem contains the mentioned array values above. Can anyone help me out?

Answer №1

Your specifications may be unclear, but fear not! I have crafted the code necessary to fulfill your request:

// Initial Array - Do not include this in your code
this.testItem = [
        {
            "key": "Testing 1",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Testing 2",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Testing 3",
            "value": "3647586/456765/345654/36789876/76"
        },
        {
            "key": "Testing 4",
            "value": "66789/74657/37485/67543"
        }
    ];


// Use the following code to alter the array `this.testItem`
var hasValueExceeding28Chars = this.testItem.some(item => item.value.length > 28);

this.testItem = hasValueExceeding28Chars
  ? this.testItem.map(item => ({
      key: item.key.replace(/Testing/g, "Test"),
      value: item.value
    }))
  : this.testItem;

console.log(this.testItem);

Voilà!

  1. Determining if any values surpass 28 characters;
  2. If so, employing the map() function of Javascript to duplicate the initial array and adjusting all keys accordingly;
  3. If not, retaining the original array intact.

Answer №2

Instead of using the word "hello", implement code to update the value

testArray.forEach(test => { if(test.value.length > 28) test.key='new value'});

Answer №3

Here is an example of how you can achieve this:

this.exampleArray =  [
        {
            "key": "Example 1",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Example 2",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Example 3",
            "value": "3647586/456765/345654/36789876/76"
        },
        {
            "key": "Example 4",
            "value": "66789/74657/37485/67543"
        }
    ];

const hasMoreThan28Chars = this.exampleArray.some(item => item.value.length > 28);

this.exampleArray = !hasMoreThan28Chars ? this.exampleArray : this.exampleArray.map((item) => 
    ({...item, key: item.key.replace("Example", "Ex")})
);

console.log(this.exampleArray)

Answer №4



let testingData = [
        {
            "label": "Test 1",
            "info": "3647586/456765/345654/36789876/76dwjdjwdn2"
        },
        {
            "label": "Test 2",
            "info": "66789/74657/37485/67543"
        },
        {
            "label": "Test 3",
            "info": "3647586/456765/345654/36789876/76"
        },
        {
            "label": "Test 4",
            "info": "66789/74657/37485/67543"
        }
    ];

testingData = testingData.map(item => {
  if (item.info.length > 28) {
    const number = item.label.substring(item.label.length - 1)
    item.label = `Test ${number}`
  }
  return item
})

console.log(testingData);

answer:

[
  {
    label: 'Test 1',
    info: '3647586/456765/345654/36789876/76dwjdjwdn2'
  },
  { label: 'Test 2', info: '66789/74657/37485/67543' },
  { label: 'Test 3', info: '3647586/456765/345654/36789876/76' },
  { label: 'Test 4', info: '66789/74657/37485/67543' }
]

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

Repeater in Angular/MVC does not allow duplicate items

Here is the code snippet that is causing the error: The JSON data structure: [ { "Id": 0, "UserName": "uniqueusername", "Photo": "base64string", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b2b ...

What is the best way to iterate through the values of nested dictionaries within a JSON file?

While working with a JSON file, I am facing a challenge trying to loop through the values of the "Location" key in dictionaries and determine the number of entries for a specific location. My loop isn't behaving as expected - sometimes it counts all t ...

Remove items from an array using other items from another array as the index

Let's consider the following scenario: let arr1 = [0,2] // This array is always sorted Just to clarify, these elements in the "arr1" array represent indexes that need to be removed from another array. We also have another array: let arrOvj = [1,4,6, ...

Utilizing Vue and Axios for advanced data filtering techniques

Struggling with an API listing project. I need to display the results of an API call and allow users to search for specific values. The displayed result is already in v-for, so filtering it again isn't an option. I'll have to make another axios c ...

Guide on how to modify a JSON file using an Azure function coded in Node.js

I have successfully accessed a JSON file from an Azure function and now I am interested in updating the same JSON file. Below is the code that I have attempted: module.exports = async function (context, myTimer) { var axios = require('axios' ...

Tips for managing errors when utilizing pipe and mergemap in Angular

In the code snippet provided, two APIs are being called. If there is an error in the first API call, I want to prevent the second API call from being made. Can you suggest a way to handle errors in this scenario? this.userService.signUp(this.signUpForm.v ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

What is the best way to configure Apache to act as a reverse proxy for an ASP.NET Core API and an Angular

My aspnet core api is running on localhost:8080 (kestrel) and functions perfectly on localhost:80 (apache reverse proxy), making it accessible from the internet via www.example.com. I am looking to deploy my angular client on the same port locahost:80(www ...

Access NgModel from NgForm

Is there a way to access the NgModel of a FormControl retrieved from the NgForm.controls object within its parent form, or directly from the form itself? Upon form submission, I pass the form as a parameter to a custom function: <form #myForm="ngForm" ...

Approach continuously activates database

The LanguageService class is injected into my components in order to retrieve translations for the component. When a key is not found in the Map, it fetches translations from the server and stores them in a Map. If the key is already in the Map, it retrie ...

PHP: Average Grade Calculated by Each Category

Having recently delved into PHP, I am facing a challenge with a class project. Despite my efforts, I am unable to figure it out, and this is the final piece of the puzzle. My dilemma revolves around a form that submits 2 arrays - ($_post['category&ap ...

When moving to a different route inside the router.events function, the browser becomes unresponsive

Within my top navbar component, I have set up a subscription to the router events: this.router.events.subscribe(event => { if (event instanceof RoutesRecognized && this.authService.isLoggedIn()) { // additional custom logic here: ...

No tests were found to run when Karma was executed using the ng test command

I'm facing an issue with my Angular 10 project where Karma is not detecting my default and custom spec.ts files for execution. Any ideas on why this could be happening? Here is a snapshot of my unchanged Karma Config file: // Karma configuration file ...

What is the best way to add unnamed functions to an array in Octave?

Can you save anonymous functions in an array? I encountered two distinct errors with different methods: f(1) = @(x) cos(x) f(2) = @(x) -sin(x) f(3) = @(x) -cos(x) f(4) = @(x) sin(x) error: operator =: no conversion for assignment of 'function handl ...

Transmitting HTML code using JSON from PHP to JavaScript

I encountered the following error while working with JS: SyntaxError: Unexpected token < in JSON at position 0 My question is, how can I effectively include HTML code (an entire page) within a JSON object? I didn't come up with this idea myself, ...

Angular2 and the exciting world of Mapbox-gl

I am currently facing an issue with integrating mapbox-gl into my Angular2 application. Despite creating the service, the app is not functioning properly. Service import {Injectable} from '@angular/core'; import * as mapboxgl from 'map ...

Count of daily features in JavaScript

Suppose there is a json document structured as follows: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "time": 1438342780, "title": "Iran's foreign minister calls for world's ...

Tips for verifying error messages in angular for nested form group fields

Hey there, I'm new to Angular and I'm working on implementing form validations. Below is the code I'm using and encountering an issue with nested form group fields. The error I'm getting in the log is "TypeError: Cannot read property &a ...

Can anyone assist in reviewing this json string array in vb.net?

{"images":[{"id":"obj_0","src":"background.jpg","width":"640","height":"480"},{"id":"obj_9","src":"elements/pipe.png","width":50,"height":44,"top":196,"left":154,"rotation":"0"},{"id":"obj_13","src":"elements/cigarette.png","width":45,"height":67,"top":168 ...

Converting a JSON string without quotes into a Map in Dart: A step-by-step guide

Is there a way to convert a JSON string without quotes to a Map in Dart? I attempted the following code on https://dartpad.dev/ but encountered an issue: import 'dart:convert'; void main() async { final String raw = "{data: {name: joy, t ...