3

Here is the code in question:

let schools = [
    { name: "Yorktown"},
    { name: "Stratford"},
    { name: "Washington & Lee"},
    { name: "Wakefield" }
];

const editName = (oldName, name, arr) => {
    return arr.map(item => {
        if (item.name === oldName) {
            return Object.assign({}, {newName: name});
        } else {
            return item
        }
    })
};

let updatedSchools = editName("Stratford", "HB Woodlawn", schools);
console.log(updatedSchools," --> updatedSchools");
console.log(schools," --> schools");

Nothing really special. However, suppose I wanted to make the key for the Object.assign something I passed in. Here, the value I have chosen is "newName"; ordinarily, of course, one would just use the exact same key and not even bother with creating a new key (that is to say, I would just say:

return Object.assign({}, {name})

But what If I wanted to pass something in. This brings up an interesting (I guess that's debatable) question though: what is the key? It's not really a string...so how would this work? My attempt to solve this will hopefully eludicate what I am trying to say:

let schools = [
    { name: "Yorktown"},
    { name: "Stratford"},
    { name: "Washington & Lee"},
    { name: "Wakefield" }
];

const editName = (oldName, name, arr, newKey = name) => {
    return arr.map(item => {
        if (item.name === oldName) {
            return Object.assign({}, {newKey: name});
        } else {
            return item
        }
    })
};

let updatedSchools = editName("Stratford", "HB Woodlawn", schools, "bear");
console.log(updatedSchools," --> updatedSchools");
console.log(schools," --> schools");

As you can see, I have passed in "bear" as my newKey (with a default parameter if not key is given). However, this doesn't work; instead of "bear" I just get the string/label newKey. I tried to work around this using template strings and such, but I couldn't seem to insert the passed in value for my new key. I am thinking this is probably not possible...but maybe someone has some ideas? Perhaps something to do with Json.stringify() or something...?

Pretty much just a curiousity question, but if anyone has some thoughts, I'd appreciate the feedback. Thanks.

  • 4
    If you're happy with using [ES2015 features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) ~ `{ [newKey]: name }` – Phil Aug 22 '17 at 06:10
  • 1
    Or in ES4, `var newObj = {}; newObj[newKey] = name` etc – FuriousD Aug 22 '17 at 06:11
  • 1
    Also, I don't see any reason to use `Object.assign` as you're only ever manipulating an empty object. You can just return the new object, ie `return { [newKey]: name }` – Phil Aug 22 '17 at 06:13

0 Answers0