73331

Destruct using titles

<h3>Question</h3>

I have answered a few questions using destructing, I just want to take this one to the next level

I want to not use reduce in this example but pure destructing if at all possible

So the data's first row contains the attribute names of the object, How can I use that to be DRY

i.e. I hoped for

const obj = data.slice(1).map((titles) => ({ titles }) )

or similar

So this works, but I miss one more step:

<pre class="snippet-code-js lang-js prettyprint-override">const data = [ ["fruits","frozen","fresh","rotten"], ["apples",884,494,494], ["oranges",4848,494,4949], ["kiwi",848,33,33] ] const titles = data[0]; // not used below but I want to use it const obj = data.slice(1).map(([fruits,frozen,fresh,rotten]) => ({ fruits,frozen,fresh,rotten }) ) console.log(obj)
<h3>Answer1:</h3>

You could map the entries for an object.

<pre class="snippet-code-js lang-js prettyprint-override">const data = [["fruits", "frozen", "fresh", "rotten"], ["apples", 884, 494, 494], ["oranges", 4848, 494, 4949], ["kiwi", 848, 33, 33]], mapWith = keys => values => Object.fromEntries(keys.map((k, i) => [k, values[i]])), getArray = ([keys, ...data]) => data.map(mapWith(keys)), array = getArray(data); console.log(array); <pre class="snippet-code-css lang-css prettyprint-override">.as-console-wrapper { max-height: 100% !important; top: 0; }

Old simpler example

<pre class="snippet-code-js lang-js prettyprint-override">const data = [ ["fruits", "frozen", "fresh", "rotten"], ["apples", 884, 494, 494], ["oranges", 4848, 494, 4949], ["kiwi", 848, 33, 33] ] const titles = data[0]; const obj = data.slice(1).map( arr => Object.fromEntries( titles.map( (t, i) => [t, arr[i]] ) ) ); console.log(obj); <pre class="snippet-code-css lang-css prettyprint-override">.as-console-wrapper { max-height: 100% !important; top: 0; }
<h3>Answer2:</h3>

You can create a curried version of zip which is similar to Object.fromEntries except that it doesn't take pairs but a list of keys and a list of values and pairs are formed based on indexes:

<pre class="lang-js prettyprint-override">zip(['a','b'], [1,2]); //=> {a: 1, b: 2})

Because it is curried you can use it in your map and avoid hardcoding titles:

<pre class="snippet-code-js lang-js prettyprint-override">const data = [ ["fruits","frozen","fresh","rotten"], ["apples",884,494,494], ["oranges",4848,494,4949], ["kiwi",848,33,33] ] const zip = keys => values => Object.fromEntries ( keys.map((k, i) => [k, values[i]]) ); const from_csv = ([titles, ...rows]) => rows.map(zip(titles)); console.log( from_csv(data) );
<h3>Answer3:</h3>

You could use reduce, but you can't really destruct...

<pre class="snippet-code-js lang-js prettyprint-override">const data = [ ["fruits","frozen","fresh","rotten"], ["apples",884,494,494], ["oranges",4848,494,4949], ["kiwi",848,33,33] ] const titles = data[0]; const obj = data.slice(1).map((row) => titles.reduce((agg, cur, index) => { agg[cur] = row[index]; return agg; }, {})); console.log(obj)
<h3>Answer4:</h3>

<pre class="snippet-code-js lang-js prettyprint-override">const data = [ ["fruits","frozen","fresh","rotten"], ["apples",884,494,494], ["oranges",4848,494,4949], ["kiwi",848,33,33] ]; const [titles, ...rest] = data; const obj = rest.map((xs) => { const o = {}; xs.forEach((x,i) => o[titles[i]] = x); return o; }); console.log(obj);

来源:https://stackoverflow.com/questions/62197270/destruct-using-titles

Recommend

  • Problem connecting to Python mail server from Java Camel application
  • Using GroupBy in Linq: Client side GroupBy is not supported
  • How to generate basic form to edit database entry quickly?
  • Tensorflow: failed to create session in server
  • Linq, VB - Anonymous type cannot be converted to anonymous type
  • Does Python have an equivalent to java.lang.Math.nextUp? [duplicate]
  • Are there circumstances where a hash algorithm can be guaranteed unique?
  • Firebase notifications in the foreground
  • GWT Popup window in new browser window
  • Is the “Async” suffix required in the name of an async ASP.NET MVC 4 action?
  • Error mysqli_select_db [closed]
  • python3.6 start 1 million requests with aiohttp and asyncio
  • hide column based on cell font color in a row vba
  • Getting The ID of a process from Process name [closed]
  • unable to render .html via spring security while .jsp works fine
  • How to connect a renderer to a specific endpoint in a viewset, and only that endpoint
  • All combinations of 1 + 2 that adds to n
  • creating buttons in skview to point to different scenes
  • How to get service executable file path
  • Encoding/decoding PDP-11 assembly language to binary and hex?
  • Speed up Date#parse & Date#strptime in Ruby, more elegant way or best practice?
  • Dynamic LINQ Multiple Where Clause
  • Spring batch pause/resume vs stop/restart
  • Specify the _id field using Bulk.IndexMany in ElasticSearch
  • Generate a runnable jar and include libraries in it with Maven
  • what do lines starting with double-slash '//' mean in a .npmrc?
  • git clone, upload-pack out of memory
  • C# code can't “see” the methods in my C++ dll
  • All Event listing on specified date in Google Calender api (V3) in java?
  • How to run chrome.tabs.insertCSS from the background page on each page?
  • How to call jQuery function in HTML returned by AJAX
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2
  • Access to a Matlab gui from the web