根据所选键从对象列表中提取对象

时间:2018-05-14 13:36:22

标签: javascript lodash

我有一个friuts列表。例如

var Fruits={
        "Banana": {
            "Price": "50",
            "quility": "good"
        },
        "Mango": {
            "Price": "100",
            "quility": "best"
        },
        "Orange": {
            "Price": "80",
            "quility": "good"
        },
        "Apple": {
            "Price": "150",
            "quility": "best"
        }
    }

并且,包含我要提取的Fruits名称的数组。例如

var SpecificFruits = ["Banana", "Mango"]

基于上面的数组,我想提取水果对象,并希望得到如下结果。

var results={
        "Banana": {
            "Price": "50",
            "quility": "good"
        },
        "Mango": {
            "Price": "100",
            "quility": "best"
            "quility": "best"
        }
    }

任何帮助/建议都将不胜感激。

6 个答案:

答案 0 :(得分:1)

您只需执行以下操作即可实现此目的:

let result = {}
SpecificFruits.forEach((fruit) => {
  if(Fruits[fruit]) {
    result[fruit] = Fruits[fruit]
  }
})

答案 1 :(得分:1)

var fruits={
    "Banana": {
        "Price": "50",
        "quility": "good"
    },
    "Mango": {
        "Price": "100",
        "quility": "best"
    },
    "Orange": {
        "Price": "80",
        "quility": "good"
    },
    "Apple": {
        "Price": "150",
        "quility": "best"
    }
}

var SpecificFruits = ["Banana", "Mango"];
var result = {};

SpecificFruits.forEach( function( fruit ){
    if( fruits[ fruit ] ){
        result[ fruit ] = fruits[ fruit ];
    }
});

console.log( result );

答案 2 :(得分:1)

var SpecificFruits = ["Banana", "Mango"];

var result = {};
SpecificFruits.forEach(function(fruit) {
  if( fruits[ fruit ] ){
    result[ fruit ] = fruits[fruit];
  }
});

答案 3 :(得分:1)

ES6

您还可以使用reduce()Object.assign()来获取所需的结果。

<强>样本

package com.company;

import java.io.*;
import java.util.Scanner;

public class Main {


// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");


public static void main(String[] args) {
    // write your code here

    boolean itsdone = false;

    String userInputFileName;
    String FirstName = null;
    String LastName = null;
    String user_junk;
    String userOutputFileName;
    String outString;

    int Age = -1;
    int rint = 0;
    int myMAX = 100;
    int MyArr2[] = new int[myMAX];
    int itemCount = 0;
    double average = 0;
    double total = 0;
    boolean ageDone = false;


    Scanner inScan = new Scanner(System.in);

    System.out.println("Enter First Name");

    FirstName = inScan.next();

    System.out.println("Enter Last Name");

    LastName = inScan.next();


    ageDone = false;
    while (!ageDone) {
        System.out.println("Enter Your Age");
        if (inScan.hasNextInt()) {
            Age = inScan.nextInt();
            System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
            ageDone = true;
        } else {
            System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
            user_junk = inScan.next();
            ageDone = false;
        }
    }

    try {
        File outputFile = new File("firstOutFile.txt");

        if (outputFile.createNewFile()){
            System.out.println("firstOutFile.txt was created"); // if file was created
        }
        else {
            System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
        }

        // --------------------------------
        // If the file creation of access permissions to write into it
        // are incorrect the program throws an exception
        //

        if ((outputFile.isFile()|| outputFile.canWrite())){
            BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));

            fileOut.write("==================================================================");

            fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);

            fileOut.write(NEWLINE +  FirstName + " " + LastName + " " + Age + NEWLINE);

            fileOut.write("==================================================================");

            fileOut.close();

        }
        else {
            throw new IOException();
        }

    } // end of try
    catch (IOException e) { // in case for some reason the output file could not be created
        System.err.format("IOException: %s%n", e);
        e.printStackTrace();
    }
} // end main method
}
var Fruits={"Banana": {"Price": "50","quility": "good"},"Mango": {"Price": "100","quility": "best"},"Orange": {"Price": "80","quility": "good"},"Apple": {"Price": "150","quility": "best"}},
    SpecificFruits = ["Banana", "Mango"];

let result = SpecificFruits.reduce((r,v)=>Object.assign(r,(Fruits[v]?{[v]:Fruits[v]}:{})),{});

console.log(result)

答案 4 :(得分:0)

您可以使用获取对象和数组键的_.pick方法,并返回一个包含数组属性的新对象。

var Fruits = {"Banana":{"Price":"50","quility":"good"},"Mango":{"Price":"100","quility":"best"},"Orange":{"Price":"80","quility":"good"},"Apple":{"Price":"150","quility":"best"}}

var SpecificFruits = ["Banana", "Mango"]
const result = _.pick(Fruits, SpecificFruits);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

答案 5 :(得分:0)

您可以通过传递初始对象和所需属性数组来使用_.pick方法。

var Fruits={ "Banana": { "Price": "50", "quility": "good" }, "Mango": { "Price": "100", "quility": "best" }, "Orange": { "Price": "80", "quility": "good" }, "Apple": { "Price": "150", "quility": "best" } }
    
var SpecificFruits = ["Banana", "Mango"]
var result = _.pick(Fruits ,SpecificFruits);
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

另一种方法是使用reduce方法编写一个没有任何库的干净解决方案。

var Fruits = {"Banana":{"Price":"50","quility":"good"},"Mango":{"Price":"100","quility":"best"},"Orange":{"Price":"80","quility":"good"},"Apple":{"Price":"150","quility":"best"}}
var SpecificFruits = ["Banana", "Mango"]

var result = SpecificFruits.reduce((fruits, elem) => { fruits[elem] = Fruits[elem]; return fruits; }, {});
console.log(result);