Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
const results = [
  {
    rating: 5,
    title: { da: 'Web udvikling', en: 'Web Development' },
    other: [1, 2, {}],
    nothing: null,
    fn: function() {}
  },
  {
    rating: 5,
    title: { da: 'Node.js', en: 'Node.js' },
    foo: {
      bar: {
        baz: { fr: 'Bonjour', en: 'Hello' }
      }
    }
  }
];
const reduceByLang = (data, lang) => {
  // Look for a `lang` key in obj or
  // if not found but still an object, recurse
  const reduceByLangObj = (obj) => {
    Object.keys(obj).forEach((key) => {
      if (obj[key] === null) {
        return;
      }
      if (obj[key][lang]) {
        obj[key] = obj[key][lang]; // replace with desired lang
      } else if (typeof obj[key] === 'object') {
        reduceByLangObj(obj[key]); // recurse
      }
    });
    return obj;
  };
  
  if (Array.isArray(data)) {
    return data.map(reduceByLangObj);
  } else {
    return reduceByLangObj(data);
  }
};
console.log(reduceByLang(results, 'da'));
console.log(reduceByLang(results, 'en')[1].foo.bar.baz);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers