1

I have a JavaScript object where one of the properties is an array. I want to modify that object to create an almost identical object, except that one property is a String instead.

Looks like the join method can be used to change an array to a String (e.g., console.log(elements.join('-'))).

But how do I create a new object that's identical to the old object, but with one property different (i.e., a string instead of an array)?

For example, I have this object, carOriginal:

{
  "make": "Ford",
  "model": "F150",
  "features": [
    "windows",
    "seatbelts"
  ]
}

... and from that I want to create this object, carNew:

{
  "make": "Chevy",
  "model": "Tahoe",
  "features": "windows,seatbelts"
}
1
  • Just to confirm I'm understanding your question correctly, you want to keep the original variable as well as create a new object in its own right, and not just overwrite the existing object, correct? Commented Jul 16, 2019 at 21:50

4 Answers 4

2

If using ES6 you can destructure the original and add new features value :

const data = {
  "make": "Ford",
  "model": "F150",
  "features": [
    "windows",
    "seatbelts"
  ]
}


const other = {...data, features: data.features.join()}

console.log(other)

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think object spread syntax was added until later in ES2018. ES2015 only supported iterable spread and rest syntax.
1

If you don't know the name of the property you have to check every value to see if it is an array:

function subJoin(obj) {
    for (let prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (Array.isArray(obj[prop])) {
                obj[prop] = obj[prop].join(',');
            }
        }
    }
    return obj;
}


let input = {
    "make": "Ford",
    "model": "F150",
    "features": [
       "windows",
       "seatbelts"
    ]
}

let output = subJoin(input);
console.log(output); /// -->  { "make": "Chevy", "model": "Tahoe", "features": "windows,seatbelts" }

Comments

0

try this:

const obj = {
  "make": "3",
  "model": "2019-07-17",
  "features": [
    "windows",
    "seatbelts"
  ]
}

const result  =  Object.assign({},obj, {features: obj.features.join()});
console.log(result);

Comments

0

You can use object rest and spread syntax to collect the rest of the keys in a separate shallow copy that the modified property will be assigned to:

const carOriginal = {
  "make": "Ford",
  "model": "F150",
  "features": [
    "windows",
    "seatbelts"
  ]
};

function transform ({ features, ...keys }) {
  return { ...keys, features: features.join() };
}

const carNew = transform(carOriginal);

console.log(carNew);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.