Adding a specific string to an object data with condition in object array

Viewed 88

I have an object array where i'm trying to modify value if it starts with '//'. If the condition is met i want to add 'https:' before that. Then the value should be like 'https://'. I have done the following. Can't figure out where the problem is.

var projects = [
{
    value: "//",
    label: "jQuery",
    desc: "the write less, do more, JavaScript library",
    icon: "jquery_32x32.png"
},
{
    value: "//",
    label: "jQuery UI",
    desc: "the official user interface library for jQuery",
    icon: "jqueryui_32x32.png"
}];
const string1 = "https:";
const objIndex = projects.findIndex(obj => obj.value.indexOf('/') === 0 ? obj.value === string1.concat(obj.value): obj.value === obj.value );console.log(objIndex);

4 Answers

You need to map() your value property and then check whether the value column startWith() the following signs //:

const result = projects.map(({value, ...rest}) => 
    ({ value: value.startsWith('//') ? `https://` : value, ...rest}))

An example:

var projects = [
  {
value: "//",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
  },
  {
value: "//",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
  }];
const string1 = 'https:';
const result = projects.map(({value, ...rest}) => ({ value: value.startsWith('//') ? `https://` : value, ...rest}))
console.log(result)

First, you have an error in string variable definition, you use different quote characters here: const string1 = 'https:"; And you can create a new array with "reduce".

let projects = [
{
    value: "//google.com",
    label: "jQuery",
    desc: "the write less, do more, JavaScript library",
    icon: "jquery_32x32.png"
},
{
    value: "//",
    label: "jQuery UI",
    desc: "the official user interface library for jQuery",
    icon: "jqueryui_32x32.png"
}];
let stringToReplace = "https:";
let objIndex = projects.reduce((arr, item) => (item.value = item.value.replace(/(\/\/.*)/, `${stringToReplace}$1`), arr.push(item), arr), []);
console.log(objIndex);

You can do it with a .forEach():

var projects = [
  {
    value: "//",
    label: "jQuery",
    desc: "the write less, do more, JavaScript library",
    icon: "jquery_32x32.png"
  },
  {
    value: "//",
    label: "jQuery UI",
    desc: "the official user interface library for jQuery",
    icon: "jqueryui_32x32.png"
  },
  {
    value: "http://",
    label: "jQuery UI",
    desc: "the official user interface library for jQuery",
    icon: "jqueryui_32x32.png"
  }];

const str = 'https:';
const target = '//';
projects.forEach(p => { if (p.value === target) { p.value = str + target } })

console.log(projects)

Here you go

projects.forEach((obj) => {
  if (obj.value === '//') {
    obj.value = 'https://';
  }
});
Related