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

时间:2020-06-15 17:29:42

标签: javascript ecmascript-6

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

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

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

y = [1, 3]

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

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

如何用Java语言实现?

4 个答案:

答案 0 :(得分:2)

您可以将array.filterarray.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);

答案 1 :(得分:0)

使用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);

输出:

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

答案 2 :(得分:0)

您可以为此使用array reduce:

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 )

答案 3 :(得分:0)

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>

输出:

enter image description here

相关问题