Home > database >  How to build a string from javascript array
How to build a string from javascript array

Time:07-06

I'm using javascript, and I have a function which generate for me an array like this :

[
 "perfumers/any(perfumer: perfumer/name eq 'Test1')",
 "perfumers/any(perfumer: perfumer/name eq 'Test2')",
 "line_unit/name eq 'EDC'",
 "line_unit/name eq 'EDT'",
 "line_unit/name eq 'EDM'",
 "line_unit/name eq 'EDK'",
 "color/name eq 'RED'",
 "color/name eq 'BLUE'",
]

and I want from this array to have string like this :

"(perfumers/any(perfumer: perfumer/name eq 'Test1') or perfumers/any(perfumer: perfumer/name eq 'Test2') )

and (line_unit/name eq 'EDC' or line_unit/name eq 'EDT' or line_unit/name eq 'EDM' or line_unit/name eq 'EDK)

and (color/name eq 'RED' or color/name eq 'BLUE')"

Do you have any idea please how can do that using javascript ?

CodePudding user response:

you can do something like this

const data = [
 "perfumers/any(perfumer: perfumer/name eq 'Test1')",
 "perfumers/any(perfumer: perfumer/name eq 'Test2')",
 "line_unit/name eq 'EDC'",
 "line_unit/name eq 'EDT'",
 "line_unit/name eq 'EDM'",
 "line_unit/name eq 'EDK'",
 "color/name eq 'RED'",
 "color/name eq 'BLUE'",
]

const transform = data => Object.values(data.reduce((res, item) => {
  const [prefix, ...rest] = item.split(' ')
  const existing = res[prefix] || []
  return {
    ...res,
    [prefix]: [...existing, item]
  }
}, {})).map(items => `( ${items.join(' or ')} )`).join(' and ')

console.log(transform(data))

CodePudding user response:

you can use a forEach loop to iterate on all array value and if string start with same value just concat them else add \n\n

const data = [
 "perfumers/any(perfumer: perfumer/name eq 'Test1')",
 "perfumers/any(perfumer: perfumer/name eq 'Test2')",
 "line_unit/name eq 'EDC'",
 "line_unit/name eq 'EDT'",
 "line_unit/name eq 'EDM'",
 "line_unit/name eq 'EDK'",
 "color/name eq 'RED'",
 "color/name eq 'BLUE'",
];

let result = '';
let prev;

data.forEach((next, it) => {

  result  = (prev && prev.split(' ')[0] === next.split(' ')[0])
    ? (!it) ? `${next}` : ` or ${next}`
    : (!it) ? `${next}` : `\n\nand ${next}`;
  prev = next;
});

console.log(result);

CodePudding user response:

here you go

  const arr=[
    "perfumers/any(perfumer: perfumer/name eq 'Test1')",
    "perfumers/any(perfumer: perfumer/name eq 'Test2')",
    "line_unit/name eq 'EDC'",
    "line_unit/name eq 'EDT'",
    "line_unit/name eq 'EDM'",
    "line_unit/name eq 'EDK'",
    "color/name eq 'RED'",
    "color/name eq 'BLUE'",
  ];

  const text=`(${[arr.filter(i=>i.startsWith('perfumers')).join(' or '),arr.filter(i=>i.startsWith('line_unit')).join(' or '),arr.filter(i=>i.startsWith('color')).join(' or ') ].join(') and (')})`;

  console.log(text);

  • Related