0

I want to be able to define a property based on another property in the same method. For example, having the url property being a copy of the name property but toLowerCase. How can I achieve this?

[
    {
        id:0,
        name:"Logitech G G512 GX Brown Türkçe RGB Mekanik Gaming Klavye",
        image:"/urun_demo/urun1.png",
        old_price:900,
        current_price:800,
        stock:10,
        url:name.toLowerCase()
    },
    {
        id:0,
        name:"SUPER/AMD RYZEN 5 3600/GIGABYTE GeForce GTX 1660 SUPER OC 6GB/16GB DDR4/500GB NV",
        image:"/urun_demo/urun2.png",
        old_price:700,
        current_price:600,
        stock:10,
        url:name.toLowerCase()

    }
]
Emin TATLI
  • 82
  • 8
  • Are you wanting an Array of all the `name` properties? Or are you asking for "Given the value of `name`, how do I find the object with that same `name` attribute?"? – Samathingamajig Jun 16 '21 at 20:46
  • Can you explain a bit more? Do you want to find all the items with 'Geforce' in the name (for example)? – Ben Stephens Jun 16 '21 at 20:48
  • i want to get the name value inside the same object, like this lets say the object looks like this { name :"aaa" ,URL:"I want to get the thisobject.name value here"} – Emin TATLI Jun 16 '21 at 20:49
  • 2
    You can't do this directly, but you could iterate over the array and set each url property. Though you could define url as a function returning a reference to name: `url: function () { return this.name.toLowerCase() }` – pilchard Jun 16 '21 at 20:53

1 Answers1

2

Loop over each element and add that property dynamically. If you want a hardcoded URL, you can do that too for a specific one since we're using the spread operator after new "url" property (so the new one would be overwritten in favor of the new one)

const computerStuff = ([
    {
        id:0,
        name:"Logitech G G512 GX Brown Türkçe RGB Mekanik Gaming Klavye",
        image:"/urun_demo/urun1.png",
        old_price:900,
        current_price:800,
        stock:10,
    },
    {
        id:0,
        name:"SUPER/AMD RYZEN 5 3600/GIGABYTE GeForce GTX 1660 SUPER OC 6GB/16GB DDR4/500GB NV",
        image:"/urun_demo/urun2.png",
        old_price:700,
        current_price:600,
        stock:10,
    }
]).map((obj) => ({url: obj.name.toLowerCase(), ...obj}));

output.innerText = JSON.stringify(computerStuff, null, 2);
html,
body {
  background: whitesmoke;
}

pre {
  margin: 1rem;
  padding: 1rem;
  border: 3px solid black;
  border-radius: 1rem;
  background: white;
  width: fit-content;
}
<pre id="output"></pre>
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34