Lodash.js – set() function

A simple Lodash.js example of the set() function, we change the 'limons' key value by specyfing the path to the key. Also if the key is non-existent then we will create the specified key in the object.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="Tizen example"/>
    <title>Tizen lodash.js example</title>
    <script src="js/lodash.min.js"></script>
</head>
<body>
<div id="first">
</div>
<br>
<div id="second">
</div>

<script>

    var firstDiv = document.getElementById('first');
    var secondDiv = document.getElementById('second');


    var firstValue = { 'food': [{ 'fruits': { 'limons': 3 } }, {'vegetables': 20}] };

  firstDiv.innerHTML = "Having the object with key value pairs:<br><br>";

  firstDiv.innerHTML += JSON.stringify(firstValue);

    var result = _.set(firstValue, 'food[0].fruits.limons', 100); // <-- second parameter is the PATH

  secondDiv.innerHTML = "...we will change the 'limons' key value using the set function and specyfing the path to the key... and we get:<br><br>";
  secondDiv.innerHTML += JSON.stringify(result);

</script>
</body>

</html>

Responses

0 Replies