skip to Main Content

I am trying to simplify an array with Javascript

[{
{name: orange,
quanity: 1},
{name: apple,
quanity: 3}
}]

I want

[{
orange:1,
apple: 3
}]

I have tried

const keys = flat.map(item => {
            item.name = item.quanity
        })

But I get

[ undefined, undefined ]

Thanks!

5

Answers


  1. You can return the key-value pairs you want in the final object from the map callback, then use Object.fromEntries to create the combined object.

    let arr=[{name:"orange",quanity:1},{name:"apple",quanity:3}];
    let res = [Object.fromEntries(arr.map(o => [o.name, o.quanity]))];
    console.log(res);
    Login or Signup to reply.
  2. Similar, but slightly different solution, compared to the one from Unmigitiated. Both are nice and short.

    let original = [
      {
        name: 'orange',
        quantity: 1
      },
      {
        name: 'apple',
        quantity: 3
      }
    ];
    
    let simpler = original
      .map(item => ({ [item.name]: item.quantity }))
      .reduce((a, c) => Object.assign(a, c), {});
    
    console.log(simpler);
    Login or Signup to reply.
  3. Note : Input given in the question is not valid JavaScript syntax

    The input given in the question is an array of objects, where each object represents a fruit and its corresponding quantity. To transform this input into the desired output, you can use the following code:

    const arr = [
      { name: "orange", quantity: 1 },
      { name: "apple", quantity: 3 }
    ];
    
    const ans = {};
    arr.forEach(({ name, quantity }) => {
      ans[name] = quantity;
    });
    

    This code initializes an empty object ans and then iterates over each object in the input array using the forEach method. For each object, it extracts the name and quantity properties and adds them to the ans object as a key-value pair.

    Login or Signup to reply.
  4. Here is another way, using .reduce():

    let original = [
      {
        name: 'orange',
        quantity: 1
      },
      {
        name: 'apple',
        quantity: 3
      }
    ];
    
    let res = original.reduce((a,{name, quantity})=>(a[name]=quantity,a),{});
    
    console.log(res);
    Login or Signup to reply.
  5. Your input data structure is not valid. You need to remove the extra curly braces, and quote the string values (and maybe spell "quantity" correctly). So you’re left with:

    const arr = [
      { name: 'orange', quantity: 1 },
      { name: 'apple', quantity: 3 }
    ];
    

    There are a few ways to get the output you want but maybe the easiest is to use a for..of loop to iterate over the array. You can then use the name and quantity values to populate the property keys/values of an output object. If you want that object to be the only element in an array you can wrap the object later.

    Note: since we don’t know if the object names are unique I’ve added an additional object to the data so you can see how the addition works in this example.

    const arr = [
      { name: 'orange', quantity: 1},
      { name: 'apple', quantity: 3},
      { name: 'orange', quantity: 32 }
    ];
    
    // Empty object
    const out = {};
    
    // Iterate over the array.
    for (const obj of arr) {
    
      // Destructure the name/quantity propertied
      // from each object
      const { name, quantity } = obj;
    
      // If the key identified by the name doesn't
      // exist on the output object create it and
      // set it to zero. This means that it doesn't matter
      // if there is more than one object with the same name.
      // If there are post-first object this line of
      // code will be ignored.
      out[name] ??= 0;
    
      // Update the property value with the
      // quantity value.
      out[name] += quantity;
    }
    
    // Wrap the object in an array
    console.log([out]);

    Additional documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search