简体   繁体   中英

how to get array from object with index as one of the object property

I have an object

const items = {
  "123": {
    "key": 123,
    "name": "one name",
    },
    "456": {
    "key": 456,
    "name": "two name",
    },
    "789": {
    "key": 789,
    "name": "three name",
    },
    };

Need to filter this from below array, with array index as object.key

const myFilter = [123,789];

Code I am trying is as below but it returning array inedx as 0,1,2... but I need the index to be object.key.

let selectedItems = myFilter.map((key) => {
        return items[key];
      });

Current output:

[0:{
  key: 123,
  name: "one name"
}, 1: {
  key: 789,
  name: "three name"
}]

Expected Output

[123:{
  key: 123,
  name: "one name"
}, 789: {
  key: 789,
  name: "three name"
}] 

jsfiddle - https://jsfiddle.net/kb374exh/2/

Your actual output is actually correct and the only possible result from mapping the myFilter array to the matching properties from items .

 const items = { "123": { "key": 123, "name": "one name", }, "456": { "key": 456, "name": "two name", }, "789": { "key": 789, "name": "three name", }, }; const myFilter = [123, 789]; const selectedItems = myFilter.map((key) => items[key]); console.log(selectedItems);

The logged output you see is including the array index. You likely are seeing the index included when logging in the browser.

在此处输入图像描述

If you want an array of objects where the original key is the new index then the best you can likely do is an array of length <highest key> and a bunch of "holes" that are simply undefined.

在此处输入图像描述

 const items = { "123": { "key": 123, "name": "one name", }, "456": { "key": 456, "name": "two name", }, "789": { "key": 789, "name": "three name", }, }; const myFilter = [123, 789]; const selectedItems = Object.entries(items).reduce((selectedItems, [key, value]) => { if (myFilter.includes(value.key)) selectedItems[key] = value; return selectedItems; }, []); console.log(selectedItems);

If you are ok with the result being an object then you can have more succinct output, you'll basically end up with back with an object with key-value pairs filtered out.

在此处输入图像描述

 const items = { "123": { "key": 123, "name": "one name", }, "456": { "key": 456, "name": "two name", }, "789": { "key": 789, "name": "three name", }, }; const myFilter = [123, 789]; const selectedItems = Object.fromEntries(Object.entries(items).filter(([, value]) => myFilter.includes(value.key))); console.log(selectedItems);

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