skip to Main Content

I have an array of color like this

var colors = ['yellow','blue']

And my data base return me

var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}]

So I wanted to show in an other array only the color which are in the color array (the first array)
This is what I want

var newArray = [{name : "Paul", yellow : "it's yellow or not", blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course",blue:"it's light blue"}]

This is what I do

    var colors = ['yellow','blue']
    var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}]

    var newArray = db.map(x => {
        var selectedColors = colors.map(y => { return { [y]: x[y] } })
        return {
            name : x.name ,
            ...selectedColors 
        }
    })

But i have something like this (example with 1 row) :

{
    0 : {yellow : "it's yellow or not"},
    1 : {blue: "it's darkblue"},
    name : "Paul"
}

but I want this

{
    yellow : "it's yellow or not",
    blue: "it's darkblue",
    name : "Paul"
}

5

Answers


  1. For each object in db, iterate over colors and take a property from the object that corresponds to the current element of colors:

    const db = [/* Your array of objects here */];
    const colors = [/* Your array of color names here */];
    
    const newArray = db.map((object) => {
      const excerpt = {
        name: object.name,
      };
    
      for (const color of colors) {
        excerpt[color] = object[color];
      }
    
      return excerpt;
    });
    

    If you care about number of lines, you could use .reduce method instead:

    const array = db.map((object) => colors.reduce((excerpt, color) => ({
      ...excerpt,
      [color]: object[color],
    }), {
      name: object.name,
    }));
    
    Login or Signup to reply.
  2. joining objects you can not have identical key names for this name you only see it 1 time

    to merge your items into one use this code :

    let newArray2 = Object.assign(...db);
    console.log(newArray2)
    
    Login or Signup to reply.
  3. You are on the right track. Either use Object.assign() as the last step:

    const dbWithFilteredEntries = db.map(({ name, ...entry }) => {
      const selectedColors = colors.map(color => ({
        [color]: entry[color]
      }));
      
      return Object.assign({ name }, ...selectedColors);
    });
    

    Try it:

    console.config({ maximize: true });
    
    const db = [
      {
        name: "Paul",
        yellow: "it's yellow or not",
        pink: null,
        red: null,
        blue: "it's darkblue"
      },
      {
        name: "Eva",
        yellow: "it's yellow of course",
        pink: null,
        red: null,
        blue: "it's light blue"
      }
    ];
    
    const colors = ['yellow', 'blue']
    
    const dbWithFilteredEntries = db.map(({ name, ...entry }) => {
      const selectedColors = colors.map(color => ({
        [color]: entry[color]
      }));
      
      return Object.assign({ name }, ...selectedColors);
    });
    
    console.log(dbWithFilteredEntries);
    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

    …or use Array#reduce():

    const dbWithFilteredEntries = db.map(({ name, ...entry}) => {
      return colors.reduce((newEntry, color) => {
        newEntry[color] = entry[color];
        return newEntry;
      }, { name });
    });
    

    This is roughly equivalent to:

    const dbWithFilteredEntries = db.map(({ name, ...entry }) => {
      const newEntry = { name };
    
      for (const color of colors) {
        newEntry[color] = entry[color];
      }
    
      return newEntry;
    });
    

    Try it:

    console.config({ maximize: true });
    
    const db = [
      {
        name: "Paul",
        yellow: "it's yellow or not",
        pink: null,
        red: null,
        blue: "it's darkblue"
      },
      {
        name: "Eva",
        yellow: "it's yellow of course",
        pink: null,
        red: null,
        blue: "it's light blue"
      }
    ];
    
    const colors = ['yellow', 'blue']
    
    const dbWithFilteredEntries = db.map(({ name, ...entry}) => {
      return colors.reduce((newEntry, color) => {
        newEntry[color] = entry[color];
        return newEntry;
      }, { name });
    });
    
    console.log(dbWithFilteredEntries);
    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
    Login or Signup to reply.
  4. The main issue with the code is that you cannot define an object if you don’t know how many fields you want. You can set a variable name and value by using square brackets (see computed property names).

    const object = {
      name: x.name,
      [colorVariable]: x[colorVariable],
    };
    

    However this doesn’t help you much if you don’t know how many (if any) colorVariables you have.

    In this scenario you want to use Object.fromEntries() to convert a list of key/value-pairs to an object.

    Object.fromEntries([["name", "Paul"], ["yellow", "yellow value"], ["blue", "blue value"]]);
    //=> { name: "Paul", yellow: "yellow value", blue: "blue value" }
    

    To create this list we can map() over a list of fields that you want to extract.

    Object.fromEntries(fields.map(field => [field, record[field]]));
    

    To do this for every object in db you’ll want to map() over each object in db as well.

    var colors = ['yellow', 'blue'];
    var db = [
      { name: "Paul", yellow: "it's yellow or not",    pink: null, red: null, blue: "it's darkblue"   },
      { name: "Eva",  yellow: "it's yellow of course", pink: null, red: null, blue: "it's light blue" },
    ];
    
    const fields = ["name", ...colors];
    const result = db.map((record) => (
      Object.fromEntries(fields.map(field => [field, record[field]]))
    ));
    
    console.log(result);

    Note that:

    db.map((record) => (
      something
    ));
    

    Is short for:

    db.map((record) => {
      return something;
    });
    
    Login or Signup to reply.
  5. You can reduce you db array like this (some explanation in comments):

    const colors = ['yellow','blue'];
    
    const db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}];
    
    const filteredOnColors = db.reduce( (acc, obj) => {
      // filter the entries of the object
      const filtered = Object.entries(obj)
        .filter(([k,]) => colors.find( color => k === color ) );
      // create a new object with the filtered values and
      // the name of the original object
      const nwObj = {...Object.fromEntries(filtered), name: obj.name};
      return [...acc, nwObj ];
    }, []);
    
    console.log(filteredOnColors);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search