Home > database >  Join elements of an object and exclude some
Join elements of an object and exclude some

Time:01-31

I have a Typescript project where I want to join all the values of an Object except one.

This is my Object:

let dataInit = {
  "host": "CAPR",
  "ua": "RMA",
  "country": "VE",
  "page":3
};

This is what I do:

let dataJoin = Object.values(dataInit).join(',')

This is what I get:

CAPR,RMA,VE,3

I need to know how to remove the 'page' property, this is what I want:

CAPR,RMA,VE

CodePudding user response:

If you don't know the other attributes, you can first use Object.entries() to give you an array of arrays containing the keys and values. That array can then be filtered to remove the "page" element, mapped to just contain the value, and finally joined.

let dataInit = {
  "host": "CAPR",
  "ua": "RMA",
  "country": "VE",
  "page":3
};

console.log(
Object.entries(dataInit)
  .filter(([key,val]) => key !== "page")
  .map(([_,val]) => val)
  .join(",")
)

CodePudding user response:

I would destructure the object first and create a new one

const { host, ua, country } = dataInit
const dataNew = { host, ua, country }

And then call the values join method on the new object.

CodePudding user response:

You could filter the array resulted:

let dataJoin = Object.values(dataInit).filter(element => typeof element === "string").join(",");

Or you can use destructuring as presented in the other comments.

CodePudding user response:

You can use for...in loop to iterate over element and skip page property.

let dataInit = {
  "host": "CAPR",
  "ua": "RMA",
  "country": "VE",
  "page": 3
};

const convertObject = (obj) => {
  let list = [];
  for (const prop in obj) {
    if (prop !== "page") {
      list.push(obj[prop]);
    }
  }
  return list.join(",");
}

console.log(convertObject(dataInit));

  •  Tags:  
  • Related