-1

I want to create an object with every value as "true" and the length of keys will be same with array length.

Example :

const myCar = [{name:ford,type:A},{name:opel,type:B}] 

The output want to be like this below

{0:true,1:true}

If the length from the array myCar will be 3 so the output will be like this as well:

{0:true,1:true,2:true}
Manfre
  • 656
  • 5
  • 12
  • 30
  • Hi! Please read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO and elsewhere, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mre] showing your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Nov 28 '22 at 10:10

4 Answers4

2

You can reduce to get a counter and an object

const myCar = [{ name: 'ford', type: 'A' }, { name: 'opel', type: 'B' }];

const myObj = myCar.reduce((acc,_,i) => (acc[i] = true,acc),{});

console.log(myObj);

Breakdown

const myObj = myCar
  .reduce(
    (acc,_,i) => // reduce passes the accumulator, the current object which we ignore here and the index
      (acc[i] = true // set the accumulator at key=index to true 
         ,acc)   // and use the comma operator to return the accumulator
     ,{});       // initialise the accumulator to an empty object
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

No one seems to be giving you the simple, straightforward approach, so: Just loop from 0 to the length of array (exclusive), adding properties to the object:

const myCar = [{name: "ford",type: "A"},{name: "opel", type: "B"}];

const result = {};
for (let index = 0; index < myCar.length; ++index) {
    result[index] = true;
}
console.log(result);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I'd say the reduce I provided is simpler - both to read and to write – mplungjan Nov 28 '22 at 10:28
  • @mplungjan - And I'd say the opposite, as would [Brian Terlson](https://twitter.com/bterlson/status/1099010861065068544) and [Jake Archibald](https://twitter.com/jaffathecake/status/1213077702300852224). `reduce` is fine in FP with reusable, tested reducer functions. Outside that, it's just an overcomplicated loop -- *especially* when you're just passing the same accumulator around, as in your answer. – T.J. Crowder Nov 28 '22 at 10:34
  • I am completely sold on the reduce or map. The compactness and setting the end variable in the same statement is so much simpler to read. Complicated reduces are not ok, but `const sum = someArray.reduce(a,b=>a+b)` instead of `let sum = 0;for (let i=0; i – mplungjan Nov 28 '22 at 11:23
  • @mplungjan - (I didn't say anything about `map`.) Well, okay, we just disagree; that's fine, the world's a big place. I've seen too many people fail to realize what will happen on an empty array without a seed, fail to return the accumulator and wonder why they got an error related to `undefined`, and too many people asking what `reduce` is "really" doing. To me, there's no contest whatsoever. – T.J. Crowder Nov 28 '22 at 11:47
0

enjoy!

const myCar = [{name:"ford",type:"A"},{name:"opel",type:"B"}] 
let obj={};
myCar.forEach((item, index)=>{
  obj={...obj,[index]:true};
})
console.log(obj);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
NAZIR HUSSAIN
  • 578
  • 1
  • 18
-1

Invalid answer:

There are a few ways to achieve what you need. You can either use Array.prototype.map to go through your original array or you can just create a new array based on your first array's length.

An example:

const myCar = [{
  name: 'ford',
  type: 'A'
}, {
  name: 'opel',
  type: 'B'
}];

const myArr = [...new Array(myCar.length)].fill('').map((_, i) => ({
  [i]: true
}));

console.log(myArr);

Quick explanation:

  • [...new Array(N)] creates an empty array with N elements
  • .fill('') fills it with some data, it does not matter what it is in your case
  • .map((_, i)) goes through each entry of the array [i]: true creates a dynamic key with a constant value true

Valid answer:

const myCar = [{
  name: 'ford',
  type: 'A'
}, {
  name: 'opel',
  type: 'B'
}];

const myArr = myCar.reduce((prev, curr, i) => ({ ...prev, [i]: true }), {});

console.log(myArr);
AbsoluteZero
  • 401
  • 7
  • 1
    That isn't the result the OP said they wanted. *(It's also much more complicated than you would need for the result you're producing. There's no need for the spread, or the `new Array`.)* – T.J. Crowder Nov 28 '22 at 10:14
  • Hey i want the final result to be object and not an array of objects – Manfre Nov 28 '22 at 10:15
  • Sorry, I misread that. Let me edit real quick. – AbsoluteZero Nov 28 '22 at 10:17
  • @T.J.Crowder What do you mean by it's much more complicated than needed? Could you provide an example of code / link to a resource that is not too complicated and it solves this issue? EDIT: I just saw your answer, nevermind. – AbsoluteZero Nov 28 '22 at 10:27
  • 1
    @AbsoluteZero - I was referring to your original incorrect answer, which can more simply be written with a loop or as `const myArr = myCar.map((_, i) => ({ [i]: true }));` -- that's what I meant about no need for spread or `new Array`. Happy coding! :-) – T.J. Crowder Nov 28 '22 at 10:37
  • @T.J.Crowder Thank you for the answer. Yeah, I mentioned `.map` as one of the options but I like to show a few ways to do stuff. The `[...new Array(N)]` stuff has helped me a few times in the past, in my opinion it's a nice bit of code to know even if it's not applicable fully in that case. Enjoy your day! – AbsoluteZero Nov 28 '22 at 10:51
  • FWIW, in situations you're using `[...new Array(N)]`, I'd probably use `Array.from({length: N})`. But horses for courses. :-) – T.J. Crowder Nov 28 '22 at 10:54
  • I know we're getting really off-topic here but you got me curious. Why would you do that? Isn't `[...new Array(N)]` faster? Not that it really matters in most cases but still I'd like to know where you preference comes from as you are a really experienced person. – AbsoluteZero Nov 28 '22 at 11:06
  • 1
    @AbsoluteZero - I doubt either is sufficiently "faster" than the other to make it worthwhile to worry about it. My primary reasons for preferring are: 1. If `N` is a large number, we avoid allocating the backing storage for that many array slots for the `new Array(N)` which we're just going to release a moment later (memory churn). (I checked with one of the V8 authors, and it does indeed preallocate in that case.) 2. To me it's just more directly saying what I want to do. This is esp. the case if you're mapping the result, because `Array.from` takes a second arg which is a mapping callback. – T.J. Crowder Nov 28 '22 at 11:39
  • Thank you, I really appreciate your answers! – AbsoluteZero Nov 28 '22 at 11:43