DEV Community

Rajasekar Thangavel
Rajasekar Thangavel

Posted on • Edited on

3 3

Loops in ES6 Javascripts


let data =
  [
    { name: 'a', content: true },
    { name: 'b', content: false },
    { name: 'c', content: true }
  ]

  const result = data.filter((item) => {
    return item.name === "a"
  })

  console.log(result);
 // [{"name":"a","content":true}]
Enter fullscreen mode Exit fullscreen mode
let data = [{ "name": "Rajasekar", "country": "India" }, 
{ "name": "Prakash", "country": "India" }, 
{ "name": "Bala", "country": "UK" }, 
{ "name": "TR", "country": "Saudi Arab" }]


for (const key in data) {
    console.log(data[key]);
}

for(const item of data) {
    console.log(item);
}

data.forEach(element => {
   console.log(element)        
});
Enter fullscreen mode Exit fullscreen mode
let val = {
    "name": "Rajkasekar",
    "title" :"rasdas"
}

for (let [key, value] of Object.entries(val)) {
    console.log(key) // name, title
    console.log(value); //Rajasekar, rasdas
}


for (const key in val) {
    console.log(val[key]); //Rajasekar, rasdas
}



Enter fullscreen mode Exit fullscreen mode

Grouping the array based on the key

const array = [{ name: "cat", value: 17, group: "animal" }, { name: "dog", value: 6, group: "animal" }, { name: "snak", value: 2, group: "animal" }, { name: "tesla", value: 11, group: "car" }, { name: "bmw", value: 23, group: "car" }];

let result = array.reduce((r, { group: name, ...object }) => {
        var temp = r.find(o => o.name === name);
        if (!temp) r.push(temp = { name, children: [] });
        temp.children.push(object);
        return r;
 }, []);

console.log(result);

[{"name":"animal","children":[{"name":"cat","value":17},{"name":"dog","value":6},{"name":"snak","value":2}]},{"name":"car","children":[{"name":"tesla","value":11},{"name":"bmw","value":23}]}]

Enter fullscreen mode Exit fullscreen mode
var user = {
  "first_name":"taylor",
  "last_name":"hawkes",
  "full_name": "taylor hawkes"
};

var userCleaned = _.pickBy(user, function(value, key) {
  return (key === "first_name" || key === "last_name");
});

//userCleaned is now:
//{
//   "first_name": "taylor",
//   "last_name": "hawkes"
//}

Enter fullscreen mode Exit fullscreen mode

ref - https://dev.to/misterkevin_js/11-ways-to-iterate-an-array-javascript-3mjg?force_isolation=true
https://youmightnotneed.com/lodash
https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more