Home > Software design >  Editing key and value from each array of objs
Editing key and value from each array of objs

Time:09-03

I have an very simple array of objs and I need to display both the key and value from each obj.

Array

sequence_break: [
        {
          "Step 4": "Step 6",
        },
      ],

I need to now display this on the page as S4 -> S6

Previously when working with an array of strings that also looked the same ["Step 2", "Step 3"], but this was easy to by using a v-for and then taking the strings and running:

S{{item.slice(5)}}

This removes the Step and space after it and then I just put an S in front of it to get the desired result.

I could've done something like str = str.slice(0, 3) str.slice(4), but I don't know if the number will ever be in double digits, so I figured adding the S was the safest bet.

Anyway, now I'm not sure how I would do that with this array of objs though and isolating the key and value from the obj. I don't know regex that well, but I'm not convinced that is the best option either.

TL;DR: How to go about turning [{ "Step 4": "Step 6" }] to S4 -> S6.

Any advice would be greatly appreciated!

Cheers!

CodePudding user response:

You could get the digit and return a new string.

const
    convert = object => Object
        .entries(object)[0]
        .map(s => 'S'   s.match(/\d $/)).join('->'),
    sequence_break = [{ "Step 4": "Step 6" }];

console.log(sequence_break.map(convert));

CodePudding user response:

I think you should reevaluate your data structures and the purpose they are serving.

The objects in the array are, in my opinion, are using a key value pair incorrectly.

Below is the code to do what you are asking:

const getStepDisplayText = (sequenceBreakArray) => {
    return sequenceBreakArray.map((sequenceBreakItem) => {
        let currentStep = Object.keys(sequenceBreakItem)[0],
            nextStep = sequenceBreakItem[currentStep];

        return `S${currentStep.split(" ")[1]} ->  S${nextStep.split(" ")[1]}`
    })
}

But consider how you might be able to get a cleaner, more simple solution by changing the structure of your data.

[
    {currentStep: "Step 4", nextStep: "Step 6"}
]
  • Related