简体   繁体   中英

How to convert an array to object in JavaScript without dependency properties

I am trying to create an array to object, it's working fine now. But, there is a dependency in to the object { ids: [], items: {} } Before I have declared the object with the required properties. I am trying to achieve the same thing without the object dependency at the beginning, initially it will be the {} not { ids: [], items: {} }

import { v4 as id } from "uuid";

export const createItem = (name) => {
  return {
    id: id(),
    name,
    packed: false
  };
};

let items = ["Backpack", "Vitamins", "Kindle"].map((x) => createItem(x));

console.log(items);

const converter = items.reduce(
  (obj, item) => {
    obj.ids.push(item.id);
    obj.items[item.id] = item;
    return obj;
  },
  { ids: [], items: {} }
);

console.log(converter);

You can use the nullish coalescing assignment operator ( ??= ) to create the initial array or object property if it does not already exist.

On the first invocation of the reducer callback, the value of the targeted properties ids and items will be undefined , so the values on the right side of the operator will be assigned to them, and the entire expression within the parentheses will evaluate to that value.

On subsequent invocations of the callback, the values will already exist at the properties, so the operator will short-circuit and the expression within the parentheses will evaluate to the existing values.

For this snippet, see also: Crypto.randomUUID()

 // import { v4 as id } from "uuid"; // UUIDv4 in the browser: const id = crypto.randomUUID.bind(crypto); const createItem = (name) => ({ id: id(), name, packed: false, }); const items = ["Backpack", "Vitamins", "Kindle"].map(createItem); const result = items.reduce( (obj, item) => { (obj.ids??= []).push(item.id); (obj.items??= {})[item.id] = item; return obj; }, {}, ); console.log(result);

Not sure what the problem with the object is. If you just want cleaner code, You can use Object.fromEntries to generate the object, if you need an array of ids you can use Object.keys on it.

const thing = Object.fromEntries(
  items.map(i => [i.id, i])
);
const converter = {ids: Object.keys(thing), items: thing};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM