0

I need to fill and object with a for, but I don't know if it's possible. The code that I've tried is this:

let objecte = {
        0: "a",
        1: "b",
        2: "c",
    };

    let prop = Object.keys(objecte);
    let valor = Object.values(objecte);

    function changePropValues(obj, prop, value){
        let newObj = {};

        for(let i=0;i<Object.keys(obj).length;i++){
            newObj = {
                valor[i]: prop[i],
            };
         }
        
        return newObj;

    };

    console.log(changePropValues(objecte,prop,valor

But I've this error: Uncaught SyntaxError: missing : after property id

It's possible fill an object with a for?

alexbaes
  • 35
  • 5
  • 3
    `Object.fromEntries(Object.entries(objecte).map(([a, b]) => [b, a]))` – Yury Tarabanko Dec 01 '20 at 10:57
  • possible duplicate with https://stackoverflow.com/questions/23013573/swap-key-with-value-json – tsu Dec 01 '20 at 11:02
  • There's a [`for..in..`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) to loop through the object keys, however, if you got `Object.keys()` extracted, you'd be much better off with something, like: `Object.keys(objecte).reduce((acc, key) => (acc[objecte[key]] = key, acc), {})`, which, I guess, would be more performant, than `Object.entries()`+`Object.fromEntries()`, by the way. – Yevhen Horbunkov Dec 01 '20 at 11:16
  • @YevgenGorbunkov - If you're going to get into microoptimization like that, just use a `for` loop and avoid the unnecessary function calls (and complexity) of using `reduce`. If you're not doing functional programming with predefined, reusable reducer functions, `reduce` is just an overcomplicated loop that's easy to get wrong, *especially* when the accumulator value doesn't change (as it doesn't above). – T.J. Crowder Dec 01 '20 at 11:31
  • @T.J.Crowder : I'm not quite sure, whether you still remembered my comment by the time started replying it. Just to be sure, I'll remind: I recommended to use `for(`-loop (`for..in..`, to be more specific) myself, as opposed to the method OP has used. – Yevhen Horbunkov Dec 01 '20 at 11:55
  • @YevgenGorbunkov - You used the bulk of your comment to suggest `reduce`, and I addressed that. I won't dignify your second comment with a reply – T.J. Crowder Dec 01 '20 at 11:59
  • @T.J.Crowder : I'm sure your great experience makes some sort of mind connection to OP to know whether *microoptimisation* is worth it or not. Personally, I wouldn't bet that some function like that may not be used for processing, say, http-requests few hundreds times a second. So just to leave it up to OP to decide, here's a [quick benchmark](https://jsbench.me/jaki5wyrkp/1). – Yevhen Horbunkov Dec 01 '20 at 12:00
  • @YevgenGorbunkov - Synthetic benchmarks are almost completely useless in JavaScript; naive, off-the-cuff ones even less so. They prove nothing here. Engines optimize code aggressively in ways specific to the implementation. Separately: I'm not a fan of snark in technical conversations. It certainly does nothing to advance your point. – T.J. Crowder Dec 01 '20 at 12:03
  • @T.J.Crowder: I didn't care whether you comment back or not starting from your very first comment, I rather addressed those, who might be tempted to use *plain old* `for(`-loops in inefficient manner just because they're terrified of `Array.prototype.reduce()` (which brings no value, except great performance and conciseness) . – Yevhen Horbunkov Dec 01 '20 at 12:06

2 Answers2

2

Yes, but what you're doing is creating a new obejct on each loop iteration. Instead, just add to the object you already have:

newObj[valor[i]] = prop[i];

(I assume your value parameter is called valor in your real code, you've changed it in one place but not another.)


Note that unless you're using changePropValues elsewhere, Yury's suggestion for doing objecte is nice and simple.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Just change the code inside for statement as follows.

newObj[valor[i]] = prop[i]
devastro
  • 79
  • 3
  • 2
    When answering you probably noticed that an already exact duplicate was already posted? – Roko C. Buljan Dec 01 '20 at 10:58
  • 1
    @alexbaes, if it works, can you tick the answer? so that others can know this is correct one. – devastro Dec 01 '20 at 10:58
  • 2
    Welcome to SO! I strongly recommend **not** pushing for OPs to accept answers, and certainly not during the first 15 minutes when they can't. :-) (Also, as Roko pointed out, this just duplicates my answer. That happens sometimes. What I usually do if the other answer was there first is delete mine.) – T.J. Crowder Dec 01 '20 at 11:02