@Speakermen

Как создать новый object из key и value?

Получается console.table(obj2.index(["a", "b", "d"]));

key 0, 1, 2 value 4, 7, 3 а должно key "a", "b", "d" value 4, 7, 3 я не могу задать keys (index)

const Series = function (arr = [] || "", index = []) {
  let arrs;
  let indexs;

  arrs = arr.length > 0 ? Object.assign({}, arr) : [];

  indexs =
    index.length > 0
      ? Object.assign({}, ...index.map((n, i) => ({ [n]: arr[i] })))
      : [];

  return {
    array: function () {
      return arrs;
    },
    index: function (value = null) {
      let result;
      if (typeof value == "string") {
        result = indexs[value];
      } else if (Array.isArray(value) || value?.length) {
        //return Object.keys(indexs).find((k) => indexs[k] === value);
        //return value.map((x, y) => y);
        //result = Object.assign(value);
        result = value.map((x) => indexs[x]);
      } else {
        result = indexs;
      }

      return result;
    },
  };
};

const obj1 = Series([4, 7, -5, 3]);
const obj2 = Series([4, 7, -5, 3], ["a", "b", "c", "d"]);

//console.table(obj2.array());
//console.table(obj2.index());
//console.table(obj2.index()["a"]);
//console.table(obj2.index("b"));
console.table(obj2.index(["a", "b", "d"]));  //{ a: 4, b: 7,  d: 3 }
  • Вопрос задан
  • 93 просмотра
Решения вопроса 1
KarnaDev
@KarnaDev
Frontend developer
Вы в index используете Object.assign для создания объекта, но не севсем правильно оборачиваете результат в map.
Я бы, честно говоря, заменила на reduce, семантически он там логичнее:
} else if (Array.isArray(value)) {
  return value.reduce((acc, key) => {
    acc[key] = indexs[key];
    return acc;
  }, {});
}

И вначале, где indexs создаете, можно тоже через reduce и c константой
const indexs = index.reduce((acc, key, i) => {
  acc[key] = arr[i];
  return acc;
}, {});

Еще я бы предложила отказаться от let arrs и indexs, вы их не переиспользуете, почему бы не сразу const
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы