1

I have an array of objects. In that array of objects I have to find which keys have empty value with index of array. Array list is given below:

let fruits=[
   {name:"apple",quantity:2,price:"" },
   {name:"orange",quantity:" ",price:"2"},
   {name:"banana",quantity:" ",price:""}
];

so here i have to find any of object key having empty value which should return key with index. i have tried using .findIndex() and other methods but unfortunately i can't. I am new to es6 and typescript. i need to check key with empty value in array of object.

James Z
  • 12,209
  • 10
  • 24
  • 44
Sathish
  • 149
  • 2
  • 19

4 Answers4

2

This should do what you want. It will "map" through your array and will find for each object the keys of properties that are empty or a blank string. Then the so filtered items are "mapped" again with all the found keys being "joined" into a comma separated list (property "f") together with the "id" of the object. As a last step I filter out all those objects where the "f" property actually contains key name(s).

let fruits=[
{name:"apple",quantity:2,price:"" },
   {name:"orange",quantity:" ",price:"2"},

{name:"pineapple",quantity:3,price:5},
   {name:"banana",quantity:" ",price:""}
   ];

let empty=fruits.map(f=>
  Object.keys(f).filter(k=>!(""+f[k]).trim()))
.map((f,i)=>({id:i,f:f.join(',')}))
.filter(f=>f.f)

console.log(empty)

In my example I added another fruit ("pineapple") with a complete set of filled properties. My snippet considers strings containing only blanks as "empty".

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
1

Please try the following example

let fruits = [
  { name: "apple", quantity: 2, price: "" },
  { name: "orange", quantity: "", price: "2" },
  { name: "banana", quantity: "", price: "" },
];

const output = fruits.reduce((previousValue, currentValue, currentIndex) => {
  const keys = Object.keys(currentValue).filter((key) => !currentValue[key]);

  if (keys.length) {
    previousValue[currentIndex] = keys;
  }

  return previousValue;
}, {});

console.log(output);

See

Mario
  • 4,784
  • 3
  • 34
  • 50
0

Assuming you're looking to get fruits that do not have a price value, you'll need to run a filter since your fruits is an array.

let emptyPriceFruits = fruits.filter((fruit) => !fruit.price)

Additional reading on .filter - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Lim Jing Rong
  • 426
  • 2
  • 4
0

How about this one, by taking entries of object and then using filter to identify deuplicate values:

var fruits=[ {name:"apple",quantity:2,price:"", pal:null }, {name:"orange",quantity:" ",price:"2"}, {name:"banana",quantity:" ",price:""}];

var emptyResult = fruits.map(k=>Object.fromEntries(Object.entries(k).filter(([k,v])=>typeof v=='string' && !v.trim())));

console.log(emptyResult);
gorak
  • 5,233
  • 1
  • 7
  • 19