繁体   English   中英

如何使用另一个数组 javascript 中的值从一个数组中检索

[英]How to retrieve from one array using the value in another array javascript

我有一个名为x的数组,如下所示。

x = [
  { id: 1, content: 'abc' },
  { id: 2, content: 'cde' },
  { id: 3, content: 'xyz' }
]

我有另一个像这样的数组y

y = [1, 3]

我想通过将x的 id 映射到y中的值来从x获取所有数据。 所以我的 output 将如下所示。

[
  { content: 'abc' },
  { content: 'xyz' }
]

如何在 Javascript 中实现这一点?

您可以使用array.filter (+一些与其他数组比较)以及array.map

 let x=[ {id: 1, content:'abc'}, {id: 2, content:'cde'}, {id: 3, content:'xyz'}]; let y=[1,3]; let result = x.filter(obj => y.some(yy => yy === obj.id)).map(({content}) => ({content})); console.log(result); //or let result2 = x.filter(obj => y.some(yy => yy === obj.id)).map(x => x.content); console.log(result2);

使用 Array.filter() 和 Array.map() 您可以获得结果。

认为:

const x = [
  {id: 1, content:'abc'},
  {id: 2, content:'cde'},
  {id: 3, content:'xyz'},
];

const y = [1,3];

const result = x.filter(item => y.includes(item.id)).map(item => {
    return {
        content: item.content
    }
});
console.log(result);

Output:

{content:'abc'}
{content:'xyz'}

您可以为此使用数组减少:

 const x = [ { id: 1, content: 'abc' }, { id: 2, content: 'cde' }, { id: 3, content: 'xyz' } ] const y = [ 1, 3 ] const result = x.reduce((a,{id,content})=> { if (y.some(eY=>eY=== id)) a.push({ content } ) return a },[]) console.log( result )

for 循环可用于提取具有匹配 ID 的元素。

这是一个使用 for 循环的工作演示:

<!DOCTYPE html>
<html>
    <head>
        <title>Demo</title>
    </head>
    <body>
        <button onclick="myFunction()">Find elements</button>
        <p id="result"></p>
        <script>
            var x = [
                {id: 1, content:'abc'},
                {id: 2, content:'cde'},
                {id: 3, content:'xyz'}
            ]

            var y = [1, 3]
            var result = []

            function myFunction() {
                for(let i = 0; i < x.length; i++) {
                    if( y.indexOf(x[i].id) >= 0 ) {
                        // Add content of matching elements to result array
                        result.push(x[i].content)
                    }
                }
                document.getElementById("result").innerHTML = result
            }
        </script>
    </body>
</html>

Output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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