0

I have created this function, however is not quite right. I get this response from it:

[
    {
        manufacturer: [
            'AUDI'
        ]
    },
    {
        body_colour: {
            'BLACK'
        }
    }
]

However what I want is:

{
    manufacturer: [
        'AUDI'
    ],
    body_colour: {
        'BLACK'
    }
}

How can I get to this? This is what I have at the moment:

checkForQueryString() {
    const urlSearchParams = new URLSearchParams(window.location.search);
    const params = Object.fromEntries(urlSearchParams.entries());

    let searchParams = Object.entries(params).map(([key, value]) => {
        return {
            [key]: value.split(',')
        }
    });
    return searchParams;
},

Query String: ?manufacturer=AUDI&body_colour=BLACK

1
  • Note theres no point doing Object.fromEntries only to then use Object.entries in the very next line Commented Aug 11, 2021 at 8:50

4 Answers 4

3

Use reduce not map

const params = {
  manufacturer: "AUDI",
  body_colour: "BLACK"
}

let searchParams = Object.entries(params).reduce((acc, [key, value]) => {
  return {
    ...acc,
    [key]: value.split(',')
  }
}, {});

console.log(searchParams)

Sign up to request clarification or add additional context in comments.

Comments

1

Object.fromEntries(urlSearchParams.entries()), Object.entries(params) are not necessary.

You can use a simple forEach function to achieve the desired result as from MDN DOCS.


function checkForQueryString() {

    const searchParams = new URLSearchParams(window.location.search);
    var result = {};
    searchParams.forEach(function(value, key) {
        result[key] = value.split(',');
    });
    return result;
}

console.log( checkForQueryString() );

When url is http:example.com?manufacturer=audi,tesla&body_colour=black,white

the output would be

{
    "manufacturer": [
        "audi",
        "tesla"
    ],
    "body_colour": [
        "black",
        "white"
    ]
}

Comments

0

Assumin you meant by your input:

body_colour: [
  'BLACK'
]

The answer can be:

let myArray = [
  {
    manufacturer: ['AUDI']
  },
  {
    body_colour: ['BLACK']
  }
];
let newObj = Object.assign({}, ...myArray)

Comments

0

You can make use of Object.fromEntries with split and map:

const str = 'manufacturer=AUDI&body_colour=BLACK';

console.log(Object.fromEntries(str.split('&').map(o=>[o.split('=')[0],[o.split('=')[1]]])));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.