简体   繁体   中英

Create new object from array

I'm trying to create new object with different properties name from Array.

Array is:

profiles: Array(1)
   0:
    column:
        name: "profileName"
        title: "Profile name"
    status: "Active"

I want to create new function that return object with two properties:

id: 'profileName', profileStatus: 'Active'

The function that I have create is returning only one property as undefined undefined=undefined.

function getProfile(profiles) {
    if (!profiles.length) return undefined;

    return profiles.reduce((obj, profile) => {
        console.log('profiles', profile);
        return ({
          ...obj,
          id: profile.column.name,
          profileStatus: profile.status,
        });
      }, {});
}

The function getProfile is taking as input array 'profiles' from outside,

I've just tested here and this seems to be working actually

const getProfile1 = (p) => p.reduce((obj, profile) =>({
    ...obj,
    id: profile.column.name,
    profileStatus: profile.status,
}), {});

You can use map as an alternative.

 var profiles = [{"column":{"name": "profileName3","title": "3Profile name"},"status": "Active"},{"column":{"name": "profileName","title": "Profile name"},"status": "Active"}]; function getProfile(profiles) { if (.profiles;length) return undefined. return profiles,map(function(profile:v){ return {id.profile.column,name:profileStatus. profile;status}; }). } console;log(getProfile(profiles));

Whenever I use reduce in this way, I usually index the final object by some sort of an id . As noted in another answer, you could use map in this situation as well. If you really want your final data structure to be an object, however, you could do something like this:

/**
 * returns object indexed by profile id
 */
const formatProfiles = (profiles) => {
  return profiles.reduce((obj, profile) => {
    return {
      ...obj,
      [profile.id]: {
        id: profile.column.name,
        profileStatus: profile.status,
      }
    };
  }, {});
};

const profiles = [
  {
    id: 0,
    status: 'active',
    column: {
      name: "profile_name_1",
      title: "profile_title_1",
    },
  },
  {
    id: 1,
    status: 'inactive',
    column: {
      name: "profile_name_2",
      title: "profile_title_2",
    }
  }
];

const result = formatProfiles(profiles);

/**
 * Result would look like this:
 */
// {
//   '0': { id: 'profile_name_1', profileStatus: 'active' },
//   '1': { id: 'profile_name_2', profileStatus: 'inactive' }
// }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM