Home > other >  how to transform value string in object to new const js
how to transform value string in object to new const js

Time:10-05

i need to convert a object with have key value to new object that contain new const named form platform and have name to value in js how to do it?

posters: [
  { platform: facebook; name: ["user test1","user test2"] },
  { platform: instagram; name: ["Ig test1","Ig test2"] },
] 

in to

posters: {
   facebook: ["user test1","user test2"] ,
   instagram: ["Ig test1","Ig test2"] ,
}

CodePudding user response:

const postersArray = [
  { platform: facebook, name: ["user test1","user test2"] },
  { platform: instagram, name: ["Ig test1","Ig test2"] }
] 
const postersObject = postersArray.reduce((previous, current) => {
            return {
              …previous,
              [current.platform]: current.name
            } 
          },{})

CodePudding user response:

  1. Your input array is invalid. There are no strings around your platform values, and you're separating your object properties with a semi-colon rather than a comma. So you would need to fix that in order to proceed.

  2. It looks as if posters is a property within a larger object so this answer will take that into account.

Use reduce on the posters array to iterate over the objects in the array and return an object where the keys are the platform names, and the values the name arrays.

Since it looks like posters is within a larger object we'll rebuild the object using the spread syntax.

const data={posters:[{platform:"facebook",name:["user test1","user test2"]},{platform:"instagram",name:["Ig test1","Ig test2"]}]};

// Create a new object
const updated = {

  // Spread out the old object into it
  ...data,

  // And replace the old `posters` property with an
  // object using `reduce`. Destructure the `platform`
  // and `name` properties from the object, and then
  // use them to add a key and a value to the initial
  // object (`acc`/accumulator)
  posters: data.posters.reduce((acc, obj) => {
    const { platform, name } = obj;
    acc[platform] = name;
    return acc;
  }, {})
};

console.log(updated);

Additional documentation

  • Related