0

How can I turn the below array

['12345', '83747']

into the below array of objects

[ {'id': '12345'}, {'id': '83747'} ]

using map?

My attempt so far, iDs is an empty array, chunk is an array of string.:

obj.iDs.concat(
            chunk.map((item) => ({
                id: item,
            })),
        );

An example, my IDE reports no issues with this code:


const body = [{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'}]

const batchGetRequestObj = {
        ids: [],
        targetProperties: ['contentID, updateDateTime'],
    };

function func() {
        try {
        chunkArray(
            body.map((item) => {
                return item.id;
            }),
            25,
        ).forEach((chunk) => {
            batchGetRequestObj.ids.concat(
                chunk.map((item) => ({
                    ids: item,
                })),
            );
            console.log(batchGetRequestObj);
        });
    } catch (e) {
        console.log(e);
    }
}

function chunkArray(array: string[], size: number) {
    const slicedArray = [];
    for (let i = 0; i < array.length; i += size) {
        slicedArray.push(array.slice(i, i + size));
    }
    return slicedArray;
}

Link to typescript playground

15
  • 1
    What have you tried so far? Commented May 2, 2021 at 21:57
  • updated with what i have so far Commented May 2, 2021 at 21:59
  • Your map is correct? What are you struggling with? Commented May 2, 2021 at 22:00
  • it outputs an empty array Commented May 2, 2021 at 22:00
  • What is chunk then? Commented May 2, 2021 at 22:01

1 Answer 1

1

You're using concat, which doesn't mutate the arrays - you'll have to set the values back to the variable

   var arr = ['12345', '83747']
   var newids = obj.ids.concat(arr.map( str => { return {"id" : str}});
   obj.ids = newids
Sign up to request clarification or add additional context in comments.

6 Comments

Thx. OP didn't have that code at the time. But I updated my answer for concat
They hadn't. (this is why I wait until someone shows an example of their effort before answering)
example added above
@notAChance - the same concat issue will happen with your updated code. See my answer above. In your new code batchGetRequestObj.ids = batchGetRequestObj.ids.concat(...
@JohnTyner thanks, I without fail ALWAYS forget this.
|

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.